3 回答
TA贡献1804条经验 获得超7个赞
这是我要在连接更改时得到通知的方法。您定义一个BroadCastReceiver来接收广播。
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = wifi != null && wifi.isConnectedOrConnecting() ||
mobile != null && mobile.isConnectedOrConnecting();
if (isConnected) {
Log.d("Network Available ", "YES");
} else {
Log.d("Network Available ", "NO");
}
}
}
您还必须BroadcastReceiver在清单文件中进行定义,并按过滤ConnectivityChange。
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
TA贡献1883条经验 获得超3个赞
补充@Dantalian的答案。从Android Nougat开始,您不应在清单上声明接收器,因为它不会接收CONNECTIVITY_ACTION
广播。您应该改为使用Context.registerReceiver(Receiver, Intent)
方法注册您的接收器。
- 3 回答
- 0 关注
- 550 浏览
添加回答
举报