0

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
febaisi
  • 644
  • 6
  • 15
  • I don't think there is a reliable solution for anything running in the background (=not foreground) on recent Android versions. – M66B Sep 03 '17 at 10:29
  • I am an android beginner. I can tell u a way but i am not sure if it works or not. Schedule a job to run when user connected to WIFI. And in that job, schedule a job to run when there is no connection (using JobInfo.NETWORK_TYPE_NONE). So I think this works because you are scheduling a job when user has wifi connection and it won't be fired immedialtey. It only gets fired when user jumped from wifi to no network. – Ajay Naredla Sep 08 '17 at 07:12
  • Pls, read my question again. NETWORK_TYPE_NONE is the default value. It will be executed right away. "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. " – febaisi Sep 11 '17 at 18:50

1 Answers1

0

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

febaisi
  • 644
  • 6
  • 15