1

I am willing to detect when the device is on WIFI to trigger a local notification.

Most of answers include having a BroadcastReceiver listen for wifi.STATE_CHANGE. However someone noted that since Android 5.0 JobScheduler offers a more efficient way of doing this:

JobInfo uploadTask = new JobInfo.Builder(mJobId,
                                         mServiceComponent /* JobService component */)
        .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
        .build();
JobScheduler jobScheduler =
        (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(uploadTask);

My app still suports 4.1, So I'm not sure if there is any way I could add the JobScheduler for versions 5.0+, and leave the static broadcast receiver in the Manifest only for the lower versions.

htafoya
  • 18,261
  • 11
  • 80
  • 104

2 Answers2

0

Small API-switch,

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
   //broadcast receiver 
}else{
   //scheduler
}

,otherwise take a look here Writing backwards compatible Android code.

Community
  • 1
  • 1
Marvin
  • 1
  • 1
  • But that broadcast receiver will be only alive during the process instance, it won't be static as if declared in the AndroidManifest.xml – htafoya Mar 08 '16 at 01:59
0

You can disable static broadcast receivers by doing:

ComponentName receiver = new ComponentName(context, myReceiver.class);
PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver, 
  PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
  PackageManager.DONT_KILL_APP); 

So then you can validate when needed by :

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
   //broadcast receiver 
}else{
   //scheduler
}
htafoya
  • 18,261
  • 11
  • 80
  • 104