Android task scheduling

  • Tutorial

Hi Habr! I bring to your attention a free translation of the article " Schedule tasks and jobs intelligently in Android " from Ankit Sinhal.


In modern application development, tasks are very often performed asynchronously, and their scope goes beyond the application life cycle. In some situations, we also have to do some work, but this does not have to be done right now. To schedule background work, Android introduced several APIs that we can correctly use in our applications.


Choosing the right scheduler can improve application performance and device battery life.


There are several APIs available for scheduling tasks on Android:


  • Alarm manager
  • Job scheduler
  • Gcm network manager
  • Firebase Job Dispatcher
  • Sync adapter

Service issues


Services allow you to perform lengthy operations in the background. Running services in the background has a very negative effect on battery power.


Services are especially harmful when they constantly use the device’s resources, even if it does not perform useful tasks.


Scheduled tasks during the application life cycle


When the application is launched, and we want to schedule or run the task at a specific time, it is recommended to use the Handler class along with Timer and Thread.


Scheduled tasks when the application is turned off


Alarm manager


AlarmManager provides access to notification services. This makes it possible to perform any operations outside the life cycle of your application. This way you can trigger events or actions, even if your application is not running. AlarmManager may start the service in the future.


We should use the AlarmManager API only for tasks that must be performed at specific times.

Usage example : suppose we want to complete a task in 1 hour or every hour. In this case, AlarmManager will help us.


Job scheduler


This is the main of all the mentioned planning options and is very effective with background work. JobScheduler API , which was introduced in Android 5.0 (API level 21).


This API allows you to perform tasks when the device has more available resources or subject to the correct conditions. All conditions can be defined when creating a task. When the declared criteria are met, the system will complete this task in the JobService of your application. JobScheduler also cancels execution, if necessary, to comply with the limitations of Doze and App Standby .


Gcm network manager


GCM (Google Cloud Messaging) Network Manager has all the schedule features from JobScheduler. GCM Network Manager is also designed to perform multiple or one-time, inevitable work while maintaining battery life.


It is used to support backward compatibility and can also be used under Android 5.0 (API level 21). Starting at API level 23 or higher, GCM Network Manager uses JobScheduler for the platform. GCM Network Manager uses the scheduling mechanism in Google Play services, so this class will only work if Google Play services are installed on the device.


Google strongly recommended that GCM users switch to FCM and instead use the Firebase Task Manager to schedule any tasks.


Firebase Job Dispatcher


Firebase JobDispatcher is also a library for scheduling background jobs. It is also used to support backward compatibility (below API 21) and works in all recent versions of Android (API 9+).


This library will also work if the device does not have Google Play services installed. In this state, this library internally uses the AlarmManager. If the device has the Google Play app available, it uses the scheduling mechanism in Google Play services.


Sync adapter


Sync adapters are designed specifically to synchronize data between the device and the cloud. It should only be used for this type of task. Synchronization can be caused by data changes in the cloud or on the device or elapsed time.
The system will try to synchronize only when the device is connected to the network.


Exercise


We have discussed enough theory, so now let's see how to use the Android Task Scheduler.


Creating a Job Service


Create a JobSchedulerService extends JobService , which requires two methods onStartJob (parameters JobParameters ) and onStopJob (parameters JobParameters ) to be created.


public class JobSchedulerService extends JobService {
   @Override
   public boolean onStartJob(JobParameters params) {
     return false;
   }
   @Override
   public boolean onStopJob(JobParameters params) {
     return false;
   }
}

The onStartJob method is called when JobScheduler decides to start your work. JobService runs in the main thread, so any logic must run in a separate thread. The onStopJob method is called if the system decides that you should stop doing your work. The method is called before jobFinished (JobParameters, boolean) .


You also need to register your service with AndroidManifest.



Create JobInfo Object


To build a JobInfo object , pass the JobService to JobInfo.Builder () , as shown below. This job designer allows you to set many different control parameters when completing a job.


ComponentName serviceName = new ComponentName(context, JobSchedulerService.class);
JobInfo jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresDeviceIdle(true)
.setRequiresCharging(true)
.build();

Scheduled task


Now we have JobInfo and JobService , so it's time to plan our work. All we need to do is schedule work with the required JobInfo , as shown below:


JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
int result = scheduler.schedule(jobInfo);
if (result == JobScheduler.RESULT_SUCCESS) {
   Log.d(TAG, “Job scheduled successfully!”);
}

Conclusion


When planning a task, you need to carefully think about when and what should cause your task, and what should happen if it fails for some reason. You have to be very careful with the performance of your application, as well as other aspects such as battery power.


JobScheduler is easy to implement and handles most for you. When using JobScheduler, our scheduled jobs are saved even if the system restarts. At the moment, the only drawback of JobScheduler is that it is only available for level 21 api (Android 5.0).


Also popular now: