Android - Network State broadcast receiver does not receive intent
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_CONNE开发者_如何学PythonCTIVITY, 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?
Try using this action instead:
Intent.ACTION_AIRPLANE_MODE_CHANGED
Edit
Or for all network state changes, use:
"android.intent.action.SERVICE_STATE"
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;
}
精彩评论