WifiManager.NETWORK_STATE_CHANGED_ACTION not received

时间:2018-12-19 11:24:38

标签: android android-intent permissions wifi state

I want to know when a device is connected to a Wi-Fi network. The problem is that I don't receive any Intent from WifiManager.NETWORK_STATE_CHANGED_ACTION

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);

    LocalBroadcastManager.getInstance(this).registerReceiver(MainActivity.wifiBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            Log.i("LOG", "onReceive"); // This is never executed
        }
    }, intentFilter);
}

Permissions

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Does WifiManager.NETWORK_STATE_CHANGED_ACTION need some others permissions?

1 个答案:

答案 0 :(得分:2)

Here LocalBroadcastManager will not work. LocalBroadcastManager will only listen to the intent send via LocalBroadcastManager. But NETWORK_STATE_CHANGED_ACTION will be broadcasted by system, so you need to register dynamic BroadcastReceiver to listen NETWORK_STATE_CHANGED_ACTION.


For example..

Define a BroadcastReceiver in your Activity as

private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            Log.i("Wi-Fi network state", info.getDetailedState().toString());
        }
    };

and register and un-register it as

@Override
    protected void onCreate(Bundle savedInstanceState) {
        ......

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }