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;
}
}
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.