开发者

Android - Network State broadcast receiver does not receive intent

开发者 https://www.devze.com 2023-03-18 14:48 出处:网络
I have a broadcast receiver that needs to listen to network changes - BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {

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;  
}
0

精彩评论

暂无评论...
验证码 换一张
取 消