Detect Network State change using JobSchedulers in Android

Mrunal picture Mrunal · May 13, 2016 · Viewed 11.8k times · Source

With Android N, You cannot statically register a Broadcast receivers for CONNECTIVITY_CHANGE intent.

From http://developer.android.com/preview/features/background-optimization.html#connectivity-action Google documentation suggest using Job Schedulers to perform this task.

Is it possible to detect network state change (LTE to wifi) and vice versa using Job Schedulers in Android?

Answer

Trevor Johns picture Trevor Johns · May 18, 2016

Yes and no.

The JobInfo.Builder.setRequiredNetworkType() method allows you to schedule jobs to run when specific network conditions are met.

The network type can be one of three values:

  • JobInfo.NETWORK_TYPE_NONE: No network connectivity required.
  • JobInfo.NETWORK_TYPE_UNMETERED: An unmetered WiFi or Ethernet connection.
  • JobInfo.NETWORK_TYPE_ANY: Any network connection (WiFi or cellular).

Now, the catch... there's no NETWORK_TYPE_CELLUAR. You can't have your app only wake up when it's only on cellular. (Why would you want to do that?)

The other catch... WiFi connections can be metered or unmetered. Metered connections are typically things like mobile hotspots, and this can either be automatically detected (there's a special DHCP option the hotspot can send), or the user can manually toggle it on a per-network basis from WiFi Settings.

So, yes, you can set network-type constraints on your JobScheduler job. However, no, you don't get the level of granularity you're asking for.

As @CommonsWare mentioned, the idea is that you usually want to schedule network-related jobs to occur when network connectivity is unmetered, unless you have a good reason. (It's also a good idea to defer jobs until AC power is available, using setRequiresCharging(true), to conserve battery.)