Reputation: 10039
I have a broadcast receiver that needs to listen to network changes -
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity =
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(!noConnectivity)
{
//some stuff
}
}
};
I register it using -
public void startListening() {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(networkStateReceiver, filter);
}
I have added the following permission in the manifest -
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The networkStateReceiver still does not receive any intent when I switch the phone to airplane mode, switch wifi off etc. Am I missing something?
Upvotes: 4
Views: 8088
Reputation: 386
You can able to use this:
At first add this before @Override
private boolean isConnected = true;
private Context c;
Then use it
//check for connectivity:
ConnectivityManager connectivityManager = (ConnectivityManager)
c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo TestConnetion = connectivityManager.getActiveNetworkInfo();
if (TestConnetion == null){
isConnected=false;
}
Upvotes: -3
Reputation: 31283
Try using this action instead:
Intent.ACTION_AIRPLANE_MODE_CHANGED
Edit
Or for all network state changes, use:
"android.intent.action.SERVICE_STATE"
Upvotes: 4