Use JobScheduler, oraclejobscheduler in Android 5.0
Use JobScheduler in Android 5.0
- Original article: using-the-jobscheduler-api-on-android-lollipop
- Translator: Mr. Simple
- Proofreader: Mr. Simple
In this article, you will learn how to use the JobScheduler API in Android 5.0. The JobScheduler API allows developers to create and execute tasks in the background when certain conditions are met.
Introduction
In Android development, there are some scenarios: You need to execute a task at a certain point in time or when certain conditions are met, such as when the device is powered on or connected to WIFI. Fortunately, in API 21 (Android 5.0, or Lollipop), google provides a new component called JobScheduler API to process such a scenario.
When a series of Preset conditions are met, the JobScheduler API performs an operation for your application. Unlike AlarmManager, the execution time is uncertain. In addition, the JobScheduler API allows multiple tasks to be executed simultaneously. This allows your application to execute certain specified tasks without considering the battery consumption caused by timing control.
In this article, you will learn more about the JobScheduler API and JobService for running a simple background task in your application, the code displayed in this article can be found in github.
1. Create a Job Service
First, you need to create an Android project with a minimum API of 21. Therefore, JobScheduler is added to Android only in the latest version. At the time of writing this article, it does not support compatible libraries.
Assume that you are using Android Studio. After you click the Create Project button, you will get a "hello world" application skeleton. The first step is to create a new java class. For simplicity, let's create a class inherited from JobService and named JobSchedulerService. This class must implement two methods:onStartJob(JobParameters params)AndonStopJob(JobParameters params);
public class JobSchedulerService extends JobService { @Override public boolean onStartJob(JobParameters params) { return false; } @Override public boolean onStopJob(JobParameters params) { return false; }}
The task is executed when the task starts.onStartJob(JobParameters params)Method, because this is used by the system to trigger a task that has been executed. As you can see, this method returns a boolean value. If the returned value is false, the system assumes that the task has been completed when this method is returned. If the returned value is true, the system assumes that the task is being executed, and the burden of executing the task falls on your shoulders. You need to calljobFinished(JobParameters params, boolean needsRescheduled)To notify the system.
When the system receives a cancellation request, the system callsonStopJob(JobParameters params)Method to cancel the task that is waiting for execution. The important thing is that ifonStartJob(JobParameters params)If false is returned, the system assumes that there is no running task when receiving a cancellation request. In other words,onStopJob(JobParameters params)In this case, it will not be called.
Note that this job service runs in your main thread, which means you need to use sub-threads, handler, or an asynchronous task to run time-consuming operations to prevent blocking the main thread. Because multithreading technology is beyond the scope of our article, let's simply implement a Handlder to execute the task we defined in JobSchedulerService.
private Handler mJobHandler = new Handler( new Handler.Callback() { @Override public boolean handleMessage( Message msg ) { Toast.makeText( getApplicationContext(), "JobService task running", Toast.LENGTH_SHORT ) .show(); jobFinished( (JobParameters) msg.obj, false ); return true; }} );
In Handler, You need to implementhandleMessage(Message msg)Method to process your task logic. In this example, we try to ensure that the example is simple, so we onlyhandleMessage(Message msg)A Toast is displayed. Here is where you want to write your task logic (time-consuming operations), such as synchronizing data.
After the task is executed, you need to calljobFinished(JobParameters params, boolean needsRescheduled)To let the system know that the task has ended. The system can add the next task to the queue. If you do not calljobFinished(JobParameters params, boolean needsRescheduled), Your task will only be executed once, and other tasks in the application will not be executed.
jobFinished(JobParameters params, boolean needsRescheduled)The params parameter in the two parameters is fromonStartJob(JobParameters params)The needsRescheduled parameter is used to let the system know whether the task should be executed repeatedly at the very bottom. This boolean value is useful because it specifies how you can handle the task execution failure caused by other reasons, such as a failed network request call.
After creating a Handler instance, you can implementonStartJob(JobParameters params)AndonStopJob(JobParameters params)To control your tasks. You may have noticed in the following code snippetonStartJob(JobParameters params)Returns true. This is because you need to control your operations through the Handler instance,
This means that the execution time of the handleMessage method of Handler may beOnStartJob (JobParameters params)Longer.Returns true, and you will let the system know that you will manually calljobFinished(JobParameters params, boolean needsRescheduled)Method.
@Overridepublic boolean onStartJob(JobParameters params) { mJobHandler.sendMessage( Message.obtain( mJobHandler, 1, params ) ); return true;}@Overridepublic boolean onStopJob(JobParameters params) { mJobHandler.removeMessages( 1 ); return false;}
Once you have done the above work in Java, you need to add a service node to AndroidManifest. xml to give your application the permission to bind and use this JobService.
<service android:name=".JobSchedulerService" android:permission="android.permission.BIND_JOB_SERVICE" />
2. Create a JobScheduler object
After JobSchedulerService is built, we can start to study how your application interacts with the JobScheduler API. The first thing you need to do is to create a JobScheduler object. In the MainActivity of the Instance code, we usegetSystemService( Context.JOB_SCHEDULER_SERVICE )A JobScheduler object called mJobScheduler is initialized.
mJobScheduler = (JobScheduler) getSystemService( Context.JOB_SCHEDULER_SERVICE );
When you want to create a scheduled task, you can useJobInfo.BuilderTo construct a JobInfo object and then pass it to your Service. JobInfo. Builder receives two parameters. The first parameter is the identifier of the task you want to run, and the second parameter is the class name of the Service component.
JobInfo.Builder builder = new JobInfo.Builder( 1, new ComponentName( getPackageName(), JobSchedulerService.class.getName() ) );
This builder allows you to set many different options to control task execution. The following code snippet shows how to set it so that your task can run every three seconds.
builder.setPeriodic( 3000 );
Other settings:
- SetMinimumLatency (long minLatencyMillis): This function allows you to set the delayed execution time (in milliseconds) of a task. This function corresponds
setPeriodic(long time)Method incompatibility. If both methods are called at the same time, an exception occurs;
- SetOverrideDeadline (long maxExecutionDelayMillis ):
This method allows you to set the latest Task latency. If other conditions are not met at the specified time, your task will also be started. AndsetMinimumLatency(long time)Similarly, this method also workssetPeriodic(long time)When both methods are called, an exception is thrown.
- SetPersisted (boolean isPersisted ):
This method tells the system whether your task will continue after your device restarts.
- SetRequiredNetworkType (int networkType ):
This method allows you to execute this task only when the specified network conditions are met. The default condition is JobInfo. NETWORK_TYPE_NONE, which means that the task will be executed no matter whether the network exists or not. The other two types are available. One is JobInfo. NETWORK_TYPE_ANY, which indicates that the task can be executed only in any network. The other is JobInfo. NETWORK_TYPE_UNMETERED, which indicates that the task will be executed only when the device is not a cellular network (for example, when a Wi-Fi connection is used.
- SetRequiresCharging (boolean requiresCharging ):
This method tells your application that this task will be executed only when the device is charging.
- SetRequiresDeviceIdle (boolean requiresDeviceIdle ):
This method tells you that the task is started only when the user is not using the device and has not been used for a period of time.
Note thatsetRequiredNetworkType(int networkType),setRequiresCharging(boolean requireCharging)AndsetRequiresDeviceIdle(boolean requireIdle)Several methods may make your task unable to be executed unless you callsetOverrideDeadline(long time)You have set the maximum latency so that your task will be executed if the conditions are met. Once your Preset conditions are set, you can build a JobInfo object and send it to your JobScheduler using the code shown below.
if( mJobScheduler.schedule( builder.build() ) <= 0 ) { //If something goes wrong}
You may have noticed that the schedule method returns an integer. If the schedule method fails, it returns an error code smaller than 0. Otherwise, it will be the id defined in JobInfo. Builder.
If your application wants to stop a task, you can callcancel(int jobId)To cancel all tasks, you can callcancelAll().
mJobScheduler.cancelAll();
Now you know how to use the JobScheduler API in your application to Perform Batch Tasks and background operations.
Conclusion
In this article, you learned how to implement a JobService subclass that uses Handler objects to run background tasks, and how to use JobInfo. Builder to set JobService. After understanding this, you can increase application efficiency while reducing resource consumption.
More Articles
For more excellent articles, click android-tech-frontier.