Translation Timed task scheduling in Android

Source: Internet
Author: User

  • Original address: Schedule tasks and jobs intelligently in Android
  • Original Ankit Sinhal
  • Translator: Phxnirvana
  • Proofread by: Ilumer, Wilsonandusa

In recent application development, asynchronous execution of tasks is very popular, and these tasks often run outside the life cycle of the app, such as downloading data or updating network resources. There are some situations where we need to do something that is not immediately necessary. Android provides some APIs to help us schedule these tasks in the app.

Choosing the right scheduler can improve the performance of your application and extend battery life.

Android M also introduced snooze mode (Doze modes) to reduce the user's battery consumption when not using the device for a short period of time.

There are several schedulers that can be used in Android:

    • Alarm Manager
    • Job Scheduler
    • GCM Network Manager
    • Firebase Job Dispatcher
    • Sync Adapter
Issues with Services

Services allows an app to perform long operations in the background, but this behavior is very power-hungry.

Service is even more harmful when you continue to use device resources without effective tasks being executed. When the backend services are listening to different system broadcasts (such as connectivity_change or new_picture ), the severity of the problem will increase.

scheduling tasks within the life cycle of an app

When the application is running, if we want to perform tasks at a specific time, it is recommended to use Handler with Timer and Thread instead of using Alarm Manger, Job Scheduler, etc. Using Handler is simpler and more efficient.

scheduling tasks outside the life cycle of an app Alarm Manager

Alarmmanager provides system-level timing services. As such, it is also a way to perform operations outside of the application life cycle. Events or actions can be triggered even if the app is not running. Alarmmanager can evoke services in the future. When a predetermined time is reached, a specific pendingintent is triggered.

Registered scheduled tasks are retained when the device sleeps (and you can choose whether to wake the device), but are emptied when shutting down and restarting.

"We should only use the Alarmmanager API when performing tasks at a specific time." This is not a way to rough check for things like device idle, network condition, or charging. ”

use case: Alarmmanager is the perfect choice if we want to perform a task or perform a task every hour after an hour. However, this API is not suitable for tasks that perform certain conditions, such as when the network is good or when it is not charged.

Job Scheduler

This is the main one of all the schedulers mentioned, and it can perform background tasks efficiently. Jobscheduler API is introduced in Android 5.0 (API level 21)

The API can perform tasks in bulk when resources are sufficient or when conditions are met. You can define prerequisites for execution when you create a task. When the condition is met, the system executes the task on the Jobservice of the app. The execution of the Jobscheduler also depends on the NAP mode of the system and the current state of the application.

The bulk execution features allow the device to hibernate more quickly and have a longer sleep period to extend battery life. In summary, this API can be used to execute any time-insensitive plan.

GCM Network Manager

GCM (Google Cloud Messaging) network manager has all the features of Jobscheduler, and GCM network Manager also uses repetitive or one-time, non-urgent tasks to extend power.

This API is backwards compatible and supports Android 5.0 (API level 21) below. Starting with API level 23, GCM Network Manager uses the Android framework's Jobscheduler. GCM Network Manager uses the Google Play service's built-in scheduler, so this class will only run on devices that have Google Play services installed .

Google strongly recommends that GCM users upgrade to FCM and use Firebase job Dispatcher to perform task scheduling.

Firebase Job Dispatcher

Firebase Jobdispatcher is also a background Task Scheduler library. The library is also used to support downward (below API level 21) and supports all recent Android devices (API level +).

This library can also be used on apps that do not have a Google play service installed but still want to dispatch tasks. At this point, the implementation inside the library is Alarmmanager. If you have a Google Play service on your device, you'll use the Google Play service's built-in scheduler.

tip: when the Google Play service is unavailable, Alarmmanager is used to support API level <= 21

If the device is API level 21, use Jobscheduler. The framework of this library is the same, so there is no functional change.

Sync Adapter

Sync adapter is specifically designed to synchronize devices and cloud data. Its use is only limited in this regard. Synchronization can be triggered when there is a change in the cloud or client data, or by a time difference or set once a day. The Android system will attempt to perform a batch sync to conserve power, and the inability to sync will be placed in the queue for later execution. The system attempts to synchronize only when it is networked.

In any case, it is recommended to use the Jobscheduler, Firebase jobdispatcher, or GCM Network Manager provided by Google.

In Android N (API level 24), SyncManager is at the top of the Jobscheduler (Task). If you need the additional functionality provided by SyncAdapter, we recommend that you use only syncadapter.

Practice

We've discussed a bunch of theoretical stuff, and here's a look at how to use Android job scheduler.

1. Create a Job Service

To build Jobschedulerservice and inherit the Jobservice class, you need to rewrite the following two methods:onstartjob (jobparameters params) and Onstopjob (jobparameters params)

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

The onstartjob (jobparameters params) method is called when Jobscheduler decides to perform a task. Jobservice works on the main thread, so any time-consuming operation should be performed on another thread. onstopjob (jobparameters params) is called when the task has not finished executing (before calling jobfinished (Jobparameters, Boolean), but the system decides to stop execution.

You also need to register the job service in the Androidmanifest

2. Create a jobinfo object

Establishing a Jobinfo object requires passing jobservice to Jobinfo.builder () , as shown below. This job builder allows you to set different options to control the execution of 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();

3. Scheduling Tasks

Now with Jobinfo and Jobservice, it's time to dispatch the task. To dispatch a task with jobinfo, you only need to execute the following code:

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!”);}

jobschedulerexample Source code can be downloaded from GitHub

Summary

When scheduling a task, you need to carefully consider the time and condition of execution and the consequences of the error. You need to trade-offs between application performance and other battery conditions.

Jobscheduler is easy to implement and deals with most complex situations. When using Jobscheduler , even if the system restarts, our task can still be executed. At the moment, the only downside toJobscheduler is that it is only available on API level (Android 5.0).

Translation Timed task scheduling in Android

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.