我使用下面的代码来检测网络更改
public class NetworkStateListener extends BroadcastReceiver {
public static int NETWORK_CONNECTED_TYPE_WIFI = 1;
public static int NETWORK_CONNECTED_TYPE_MOBILE = 2;
public static int NO_NETWORK_CONNECTIVITY = 0;
public static int TYPE_NOT_KNOWN = -1;
private static final List<NetworkStateChangeListener> LISTENERS = new CopyOnWriteArrayList<>();
@Override
public void onReceive(Context context, Intent intent) {
int status = getConnectivityStatus(context, intent);
networkChecking(status);
}
private void networkChecking(int noNetworkConnectivity) {
for (NetworkStateChangeListener mlistener : LISTENERS) {
if (mlistener != null) {
mlistener.onNetworkStateChanged(noNetworkConnectivity);
}
}
}
public static void registerNetworkState(NetworkStateChangeListener listener) {
synchronized (LISTENERS) {
if (!LISTENERS.contains(listener)) {
LISTENERS.add(listener);
}
}
}
public static void unregisterNetworkState(NetworkStateChangeListener listener) {
LISTENERS.remove(listener);
}
public static int getConnectivityStatus(Context context, Intent intent) {
if (intent.getExtras() != null) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork!=null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
return NETWORK_CONNECTED_TYPE_WIFI;
}
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
return NETWORK_CONNECTED_TYPE_MOBILE;
}
}
return NO_NETWORK_CONNECTIVITY;
}
return TYPE_NOT_KNOWN;
}
}
并初始化AndroidManifest.xml中的intent过滤器
<receiver android:name=".utils.network.NetworkStateListener">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
此代码适用于Marshmallow设备6.0.1以下。但从7牛轧糖开始,它不起作用。
Nougat的代码变化是什么?
任何代码或要点将不胜感激。提前谢谢。
答案 0 :(得分:1)
找到解决方案:
以编程方式注册
IntentFilter intentFilter = new IntentFilter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // **For Nougat**
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
} else {
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_CHANGE));
}
registerReceiver(new NetworkConnectionReceiver(), intentFilter);