Skip to content Skip to sidebar Skip to footer

Wifi Connectivity Changed Broadcast Receiver Repeats Multiple Times

I have the following Broadcast receiver. public class TestNetworkReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {

Solution 1:

The broadcast [CONNECTIVITY_ACTION ] seems to be sticky on few devices hence when you register the receiver it will immediately call onReceive() with the most recently sent broadcast.

Hence it is recommended that you need to do static declaration of receiver on manifest.

This is what i have used :

@OverrideprotectedvoidonResume() {
    super.onResume();
    setMyReceiverStayus(PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
}

@OverrideprotectedvoidonPause() {
    super.onPause();
    setMyReceiverStayus(PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
}


privatevoidsetMyReceiverStayus(int receiverState) {
    ComponentNamereceiver=newComponentName(this, MyReceiver.class);
    PackageManagerpm=this.getPackageManager();
    pm.setComponentEnabledSetting(receiver, receiverState,       
    PackageManager.DONT_KILL_APP);
}

AndroidManifest.xml

<receiverandroid:name="com.example.receiver.MyReceiver"><intent-filter><actionandroid:name="android.net.conn.CONNECTIVITY_CHANGE" /></intent-filter></receiver>

Solution 2:

You can try this

publicclassTestNetworkReceiverextendsBroadcastReceiver {
    publicstaticbooleanfirstTime=true;

    @OverridepublicvoidonReceive(Context context, Intent intent) {

        StringTAG="TEST:";

        if (firstTime) {
            firstTime = false;
            //do stuff
        }
    }
}

Probably not the most elegand way but it does the trick

Solution 3:

A late post might be useful for someone wanting to do some background activity from connection up/down handler and maintain the thread safety.

I used AtomicBoolean variable,

private AtomicBoolean networkUp = new AtomicBoolean(false);

privatevoidonConnectivityUp() {
    Log.d("TAG", "onConnectivityUp");

    if (networkUp.compareAndSet(false, true)) {
        // Do something
    } else {
        // Duplicate event ignoring
        Log.d("TAG", "onConnectivityUp - ignoring");
    }
}

privatevoidonConnectivityDown() {
    Log.d("TAG", "onConnectivityDown");
    if (networkUp.compareAndSet(true, false)) {
        // Do something
    } else {
        // Duplicate event ignoring
        Log.d("TAG", "onConnectivityDown - ignoring");
    }
}

PS: onConnectivityUp and onConnectivityDown are getting called from my broadcast receiver

Solution 4:

When toggling wifi, the broadcast is received many times because of multiple wifi state changes. You can use getWifiState to receive these updates.

You will need to add the permissions for ACCESS_WIFI_STATE, in the manifest file, since app is accessing the wifi state.

<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" /><application....
    <activityandroid:name=".MainActivity">
      ....
    </activity></application>

Example:

In BroadcastReceiver class,

@OverridepublicvoidonReceive(Context context, Intent intent) {

    Log.i("[Broadcast]", "intent - " + intent.getAction());

    switch (intent.getAction()) {
        case WifiManager.WIFI_STATE_CHANGED_ACTION:
            ReceivedWifiStateChangedAction(context, intent);
            break;

        default:
            Log.i("[Broadcast]", "Default case!!");
    }
}


privatevoidReceivedWifiStateChangedAction(Context context, Intent intent) {

    WifiManagerwifi= (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    switch (wifi.getWifiState()) {

        case WifiManager.WIFI_STATE_DISABLED:
            Log.i("[Broadcast]", "WIFI_STATE_DISABLED");
            break;

        case WifiManager.WIFI_STATE_DISABLING:
            Log.i("[Broadcast]", "WIFI_STATE_DISABLING");
            break;

        case WifiManager.WIFI_STATE_ENABLED:
            Log.i("[Broadcast]", "WIFI_STATE_ENABLED");
            break;

        case WifiManager.WIFI_STATE_ENABLING:
            Log.i("[Broadcast]", "WIFI_STATE_ENABLING");
            break;
    }
}

In Activity class,

privatestatic Receiver myReceiver;

// Register broadcastspublicvoidRegisterBroadcast () {

    myReceiver = new Receiver();
    IntentFilter filter = new IntentFilter();

    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

    registerReceiver(myReceiver, filter);
}

Output:

When switching on the wifi,

I/[Broadcast]: intent-android.net.wifi.WIFI_STATE_CHANGEDI/[Broadcast]: WIFI_STATE_ENABLINGI/[Broadcast]: intent-android.net.wifi.WIFI_STATE_CHANGEDI/[Broadcast]: WIFI_STATE_ENABLED

You can discard the ENABLING/DISABLING broadcast and use ENABLED/DISABLED broadcast.

Solution 5:

publicvoidonReceive(Context context, Intent intent) {
     ConnectivityManagercm= (ConnectivityManager)  
     context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfoinfo= cm.getActiveNetworkInfo();
        if (info != null) {
            if (info.isConnected()) {
                // you got a connection! tell your user!
                Log.i("Post", "Connected");

            }
        } 
    }

add this to the manifest

<receiverandroid:name="packageName.ConnectivityDetector_Receiver" ><intent-filter><actionandroid:name="android.net.conn.CONNECTIVITY_CHANGE" /></intent-filter></receiver>

Try this

Post a Comment for "Wifi Connectivity Changed Broadcast Receiver Repeats Multiple Times"