I am trying to figure out how do I detect wifi state change while my app is in the background. To give a summary of my issue. In my activity I register a receiver OnStart()such that :
IntentFilter networkIntent = new IntentFilter();
networkIntent.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkIntent.addAction("android.net.wifi.WIFI_STATE_CHANGED");
registerReceiver(wifichangereceiver, networkIntent);
and then I define my wifichangereceiver fn :
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()) {
isConnectedtoWifi = true;
if (MyCallisInConnectedState()) {
onNetworkStateChanged(true);
}
} else {
isConnectedtoWifi = false;
}
}
};
and I unregister it in Onstop() :
unregisterReceiver(wifichangereceiver);
However, this mechanism works ONLY when the app is in foreground since I am registering and unregistering in my activity itself. Is there any easier way to monitor the wifi status when the call is in background aswell (or possibly thoughout? ) I tried adding a receiver in manifest but not sure if that is the correct approach. I want to be able to tell when my wifi state changes.Any ideas?