Android - Network State broadcast receiver does not receive intent

旧城冷巷雨未停 提交于 2019-12-06 05:50:45

问题


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?


回答1:


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



回答2:


Try using this action instead:

Intent.ACTION_AIRPLANE_MODE_CHANGED

Edit

Or for all network state changes, use:

"android.intent.action.SERVICE_STATE"



来源:https://stackoverflow.com/questions/6615245/android-network-state-broadcast-receiver-does-not-receive-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!