📜 ⬆️ ⬇️

Scheduling tasks in Android

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


In modern application development, tasks are often performed asynchronously, and their volume goes beyond the life cycle of the application. In some situations, we also need to do some work, but this is not necessarily done right now. To schedule background work, Android introduced several APIs that we can competently 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:



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 device resources, even if they do not perform useful tasks.


Scheduled tasks during the application life cycle


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


Scheduled tasks with the application 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 must use the AlarmManager API only for tasks that need to be performed at a specific time.

Example use : Suppose we want to complete a task after 1 hour or every hour. In this case, AlarmManager will help us.


Job scheduler


This is one of the foremost planning options mentioned and very effective with background jobs. 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 when the correct conditions are met. All conditions can be defined when creating a task. When the announced criteria are met, the system will perform this task in the JobService of your application. JobScheduler also cancels the execution, if necessary, in order to comply with the restrictions of the Doze mode 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, imminent 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 encouraged GCM users to 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 there are no installed Google Play services on the device. In this state, this library internally uses the AlarmManager. If a Google Play application is available on the device, it uses the scheduling mechanism in Google Play services.


Sync adapter


Sync adapters are designed specifically for data synchronization 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 by elapsed time.
The system will try to synchronize only when the device is connected to the network.


Exercise


We discussed a lot of theory, so now let's see how to use the Android Task Scheduler.


Create Job Service


Create a JobSchedulerService extends JobService that requires two onStartJob ( JobParameters parameters) and onStopJob ( JobParameters parameters) 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. The JobService runs in the main thread, so any logic must be executed in a separate thread. The onStopJob method is called if the system has decided that you must stop doing your work. The method is invoked before jobFinished (JobParameters, boolean) .


You also need to register your service in AndroidManifest.


 <application> <service android:name=”.JobSchedulerService “ android:permission=”android.permission.BIND_JOB_SERVICE” android:exported=”true”/> </application> 

Create a JobInfo object


To build a JobInfo object, pass the JobService to JobInfo.Builder () , as shown below. This task designer allows you to set a variety of different control parameters when performing a task.


 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 the job 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 think carefully about when and what should trigger your task, and what should happen if it does not work for some reason. You must be very careful with the performance of your application, as well as other aspects, such as battery power.


JobScheduler is easily implemented and handles most of it for you. When using JobScheduler, our scheduled tasks are saved, even if the system reboots. At the moment, the only drawback of JobScheduler is that it is available only for level 21 api (Android 5.0).


')

Source: https://habr.com/ru/post/336120/


All Articles