Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Job-Schedulers in Android

Job-Schedulers in Android

Doing a job in background is very critical, specially with Doze mode and App stand by. In this presentation I have explained how can you schedule a job intelligently and conserve user's battery and network data.

Deesha Vora

March 24, 2018
Tweet

More Decks by Deesha Vora

Other Decks in Programming

Transcript

  1. What’s JobScheduler ? Job Service The work you are wanting

    to do. Extends Job Service class. Job runs on main thread. Need to implement • onStartJob() • jobFinished() Job Info Job Info object is conditions under which Job service will execute. Need to Give • JobID • JobService • Criteria(s) for trigger. [Network, Charging/Idle, Content URI (API 24), Backoff-Policy, Periodic] Job Scheduler Job Scheduler is used to schedule the job. schedule() call using JobInfo object and Job with similar ID will be replaced.
  2. JOB SERVICE public class MyJobService extends JobService { boolean isWorking

    = false; boolean jobCancelled = false; // Called by the Android system when it's time to run the job @Override public boolean onStartJob(JobParameters jobParameters) { Log.d(“TAG”, "Job started!"); isWorking = true; startWorkOnNewThread(jobParameters);
  3. JOB SERVICE // Services do NOT run on a separate

    thread return isWorking; } private void startWorkOnNewThread(final JobParameters jobParameters) { new Thread(new Runnable() { public void run() { doWork(jobParameters); } }).start(); }
  4. JOB SERVICE private void doWork(JobParameters jobParameters) { // 10 seconds

    of working (1000*10ms) for (int i = 0; i < 1000; i++) { // If the job has been cancelled, stop working; the job will be rescheduled. if (jobCancelled) return; try { Thread.sleep(10); } catch (Exception e) { } } Log.d(TAG, "Job finished!"); isWorking = false; boolean needsReschedule = false; jobFinished(jobParameters, needsReschedule); }
  5. JOB SERVICE // Called if the job was cancelled before

    being finished @Override public boolean onStopJob(JobParameters jobParameters) { Log.d(TAG, "Job cancelled before being completed."); jobCancelled = true; boolean needsReschedule = isWorking; jobFinished(jobParameters, needsReschedule); return needsReschedule; } }
  6. SET UP JOB INFO ComponentName componentName = new ComponentName(this, MyJobService.class);

    JobInfo jobInfo = new JobInfo.Builder(12, componentName) .setRequiresCharging(true) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) .build();
  7. Time to Schedule JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE); int resultCode =

    jobScheduler.schedule(jobInfo); if (resultCode == JobScheduler.RESULT_SUCCESS) { Log.d(TAG, "Job scheduled!"); } else { Log.d(TAG, "Job not scheduled"); }
  8. Intelligent Jon-Schedulers Scheduling this work intelligently can improve your app’s

    performance Note: Use Handler if app is in foreground AlarmManager GCM Network Manager Firebase JobDispatcher SyncAdapter Services
  9. Alarm Manger • We should only use AlarmManager API for

    tasks that must execute at a specific time or after specific time. • This does not provide more robust execution conditions like device is idle, network is available or charging detect.
  10. GCM Network Manager • Has all the schedule features from

    JobScheduler. • Can also use below Android 5.0 (API level 21). From API level 23 or higher, GCM Network Manager uses the framework’s JobScheduler. • Uses the scheduling engine inside Google Play services • Google has strongly recommended for GCM users to upgrade to FCM and instead use Firebase Job Dispatcher for scheduling any tasks.
  11. Firebase Job Dispatcher • supports backward compatibility (below API 21)

    & works on all recent versions of Android (API 9+). • If device do not have Google play services installed , this library internally uses AlarmManager. If Google Play service is available on the device then it uses the scheduling engine inside Google Play services. • It uses AlarmManager to support API levels <= 21 if Google Play services is unavailable. For the device running on API level 21, it uses JobScheduler
  12. Sync Adapter • Sync adapters are designed specifically for syncing

    data between a device and the cloud. • The Android system will try to batch outgoing syncs to save battery life and transfers that are unable to run will queue up for transfer at some later time • Android N (API level 24), the SyncManager sits on top of the JobScheduler. You should only use the SyncAdapter class if you require the additional functionality that it provides.
  13. DOZE & APP Stand by restrictions • The system ignores

    wake locks. • The system does not allow sync adapters to run. • The system does not allow JobScheduler to run • Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window. ◦ The system does not perform Wi-Fi scans. • Network access is suspended.
  14. DOZE & APP Standby solutions Alarm Manger • API 23

    introduces two new AlarmManager methods: setAndAllowWhileIdle() and setExactAndAllowWhileIdle(). If the device is idle for long periods of time, the system allows idle apps network access around once a day • Whitelist request for the app, to allow partial wake lock • Acceptable whitelist cases
  15. Data cost sensitivity Job-Schedulers in Android P • With Android

    P, JobScheduler has been improved to let it better handle network-related jobs for the user, in coordination with network status signals provided separately by carriers. • Jobs can now declare their estimated data size, signal prefetching, and specify detailed network requirements—carriers can report networks as being congested or unmetered.
  16. Data cost sensitivity … • When adding jobs, make sure

    to use setEstimatedNetworkBytes(), setIsPrefetch(), and setRequiredNetwork() • When your job executes, be sure to use the Network object returned by JobParameters.getNetwork()
  17. Thank you ! By Deesha Vora (@Deesharv) Co-founder & Chief

    of Product @SuperWiseSite Email: [email protected] Job-Scheduler libraries https://github.com/evernote/android-job https://github.com/yigit/android-priority-jobqueue