Reputation: 1385
I am using below code to detect network changes
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;
}
}
and initialising below intent filters in AndroidManifest.xml
<receiver android:name=".utils.network.NetworkStateListener">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
This code is working fine for below Marshmallow devices 6.0.1. But from 7 Nougat onwards, its not working.
What is the code change in Nougat?
Any code or gist will be appreciated. Thanks in advance.
Upvotes: 0
Views: 134
Reputation: 159
Find the solution:
Register programmatically like this
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);
Upvotes: 1