How do I detect network state /wifi state has changed while my app is in the background?

Viewed 456

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?

2 Answers

If your app targets API level 26 or higher, you've to use a foreground service to do any long-running task even when the user isn't interacting with the app. Since Android Oreo, The system imposes restrictions on running background services when the app itself isn't in the foreground. For performing short living tasks in the background, your app should use a scheduled job instead.

You may refer this training doc to understand how it works for your requirement.

Related