0

I want to detect if my wifi connection has changed(if it has changed to cellular or some other wifi but not the same) after I return to the app from background. Is there any way to do this? I tried the below code but it doesn't work, it keeps firing up every single time i return to the app even if the same wifi stays connected.

 IntentFilter networkIntent = new IntentFilter();
        networkIntent.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkIntent.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        registerReceiver(wifichangereceiver, networkIntent);

Below is my receiver:

public final BroadcastReceiver wifichangereceiver = new BroadcastReceiver() {


        @Override
        public void onReceive(final Context context, final Intent intent) {
            final ConnectivityManager connMgr = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            final android.net.NetworkInfo wifi = connMgr
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (wifi.isConnected()) {
                hasWifiChanged = true;
              } else {
                hasWifiChanged = false;
              }
}

1 Answers1

0

Why not register the wifi ID in a variable and then when you connect to WiFi, you can compare the new wifi ID to the old one?

 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
 WifiInfo wifiInfo = wifiManager.getConnectionInfo();
 String ssid = wifiInfo.getSSID();
 int networkid = wifiInfo.getNetworkId();

If networkid is returning O on your device, just use the SSID instead.

Ali Elgazar
  • 777
  • 2
  • 12
  • 26
  • I call it in an activity which gets destroyed when I background the app though. Is there a way I can retain the value? –  Oct 02 '18 at 15:33
  • @MarissaNicholas There are many ways. Simplest would be to use shared preferences, full tutorial can be found here https://developer.android.com/training/data-storage/shared-preferences. Shared preferences lets you save a key-value pair, and fetch it from any activity. – Ali Elgazar Oct 02 '18 at 17:26
  • i will give it a try, tried another approach, but need to scratch that soon –  Oct 04 '18 at 01:36
  • the bounty is yours. Never tried the method but I am sure it works based on logic. i couldnt try it anymore coz the company i worked for just shut down :\ –  Oct 06 '18 at 15:05