Detect user has disconnected of the Wifi in Android Nougat

500 Views Asked by At

When an app is in background mode, how can we detect that the user has disconnected of the Wi-Fi?

As everybody knows, after Android 7.0, our BroadcastsReceveirs are no longer fired when a CONNECTIVITY_ACTION broadcast intent is sent. Register the BroadcastReceiver manually/programmatically is not an option since my application is running in the background.

I tried to schedule a JobService, that works well when the user jumps in a Wi-Fi network (NETWORK_TYPE_UNMETERED requirement), but it doesn't work when the user jumps out of WiFi straight to a state with no internet, at all. Like if the user has NO SIM Card.

JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(new JobInfo.Builder(JOB_ID,
   new ComponentName(this, NoInternetJobService.class))
   .setRequiredNetworkType(JobInfo.NETWORK_TYPE_METERED)
   .build());

With above example, my JobService would be fired if the user jumped out of the WiFi and gets connected to a METERED connection (SIM Card with data on).

Some of you can say, use the JobInfo.NETWORK_TYPE_NONE for the network requirement, but that is just the default value for a scheduled job. I am basically saying to the jobScheduler to not look into the network parameters to run my job, because I don't need internet at all. So it would be executed at the moment that I schedule it since I don't have any other requirements.

Any thoughts? I am starting to think that it can't be done in Nougat or higher.

1

There are 1 best solutions below

0
On

Solution - Listen to android.net.wifi.STATE_CHANGE broadcast instead of android.net.conn.CONNECTIVITY_CHANGE intents.