Search code examples
androidbroadcastreceiver

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) {

        String TAG = "TEST:";

        if (intent.getAction().equals("android.net.wifi.WIFI_STATE_CHANGED")) {

            Log.i(TAG, "Wifi toggled");

        } else if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {

            Log.i(TAG, "Network connection changed");

            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = cm.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {

                Log.i(TAG, "Network connecion is:" + networkInfo.getTypeName());

                Log.i(TAG, "Detail:"+networkInfo.isFailover());
            }
        }
    }
}

When I toggle the wifi on and off

I/TEST:﹕ Wifi toggled
I/TEST:﹕ Network connection changed
I/TEST:﹕ Network connecion is:WIFI
I/TEST:﹕ Detail:false
I/TEST:﹕ Network connection changed
I/TEST:﹕ Network connecion is:WIFI
I/TEST:﹕ Detail:false
I/TEST:﹕ Network connection changed
I/TEST:﹕ Network connecion is:WIFI
I/TEST:﹕ Detail:false

I/TEST:﹕ Network connection changed
I/TEST:﹕ Network connecion is:mobile
I/TEST:﹕ Detail:true
I/TEST:﹕ Network connection changed
I/TEST:﹕ Network connecion is:mobile
I/TEST:﹕ Detail:true

What I'm trying to achieve is to know when the connection goes "mobile" or "wifi" and is active but only once. Otherwise it runs my routine 3 or 4 times. I've tried changing networkInfo.whatever() but everything repeats 3 or 4 or more or less times. Is there a way I can just know the connection has changed and what it is only one time somewhere in the receiver?


Solution

  • You can try this

    public class TestNetworkReceiver extends BroadcastReceiver {
        public static boolean firstTime = true;
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            String TAG = "TEST:";
    
            if (firstTime) {
                firstTime = false;
                //do stuff
            }
        }
    }
    

    Probably not the most elegand way but it does the trick