Search code examples
androidbroadcastreceiverandroid-broadcastnetwork-connection

Not able to receive network related events


I have registered to ConnectivityManager.CONNECTIVITY_ACTION BroadcastReceiver, for receiving network state events, but my onReceive function is not getting called when I turn on or off my wifi connection.

As mentioned in the docs, this is an Sticky Broadcast Receiver which gets fired when we register for it.

But I am not getting any events in my onReceive function when I register for this receiver, what might be the cause?

In my Manifest file, I have all the permissions for accessing Internet/Network/Wifi connections and their states.

I am registering with this intent using following code:

registerReceiver(mNetworkStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

In my Logcat, I get following Error Message register for this broadcast receiver:

01-01 00:05:29.804: ERROR/WifiHW(1305): Unable to open connection to supplicant on "/data/system/wpa_supplicant/wlan0": Connection refused

What might be the cause? Is there any way of finding out whether BroadcastReceiver is registered properly or not?

Thanks.


Solution

  • This works for me:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    <receiver android:name=".receiver.ConnectivityReceiver">
       <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
       </intent-filter>
    </receiver>
    

    Code:

    public class ConnectivityReceiver extends BroadcastReceiver {
    
      @Override
      public void onReceive(Context context, Intent intent) {
          Log.d(ConnectivityReceiver.class.getSimpleName(), "action: "
                  + intent.getAction());
      }
    }
    

    and do not forget registering all network permission.