Using JobScheduler in Android 5.0
•Original link:using-the-jobscheduler-api-on-android-lollipop
•Translator:
•Proofreader:
In this article, you will learn how to use the JobScheduler API in Android 5.0. The JobScheduler API allows developers to create tasks that execute in the background when certain criteria are met.
introduce
In Android development, there are scenarios where you need to perform a task at a later point in time or when a specific condition is met, such as when the device is turned on the power adapter or connected to WIFI. Fortunately, in API 21 (Android 5.0, Lollipop), Google provides a new component called the JobScheduler API to handle such scenarios.
When a series of preset conditions are met, the JobScheduler API performs an action for your application. Unlike AlarmManager, this execution time is uncertain. In addition, the JobScheduler API allows multiple tasks to be executed simultaneously. This allows your application to perform certain specified tasks without taking into account timing controls into account battery consumption.
In this article, you will learn more about the JobScheduler API and the JobService used to run a simple backend task in your application. The code shown in this article you can usegithubFound in.
1. Create a Job Service
First, you need to create an Android project with a minimum API of 21, so JobScheduler has only been added to Android in the recent version. When writing this article, it did not have the compatible library support.
Assuming you are using Android Studio, when you click the completion button to create the project, you will get a "hello world" application skeleton. The first step you have to do is create a new Java class. For simplicity, let's create a class inherited from JobService and named JobSchedulerService. This class must implement two methods, namelyonStartJob(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 onStartJob(JobParameters params) method is executed when the task starts because this is used by the system to trigger the task that has been executed. As you can see, this method returns a boolean value. If the return value is false, the system assumes that the task has been executed when this method returns. If the return value is true, then the system assumes that the task is about to be executed and the burden of executing the task falls on your shoulders. When the task is executed, you need to call itjobFinished(JobParameters params, boolean needsRescheduled)to notify the system.
When the system receives a cancel request, the system will callonStopJob(JobParameters params)Method cancels the task waiting for execution. It is very important that ifonStartJob(JobParameters params)Return false, then the system assumes that there is no running task when a cancel request is received. in other words,onStopJob(JobParameters params)In this case, it will not be called.
It should be noted that this job service runs on your main thread, which means you need to use a child thread, handler, or an asynchronous task to run time-consuming operations to prevent blocking the main thread. Because multithreading technology has exceeded the scope of our article, let us simply implement a Handlder to perform the tasks we defined in the JobSchedulerService.
private Handler mJobHandler = new Handler( new () { @Override public boolean handleMessage( Message msg ) { ( getApplicationContext(), "JobService task running", Toast.LENGTH_SHORT ) .show(); jobFinished( (JobParameters) , false ); return true; } } );
In Handler, you need to implement the handleMessage(Message msg) method to handle your task logic. In this example, we try to ensure that the example is simple, so we only display a Toast in handleMessage(Message msg), which is where you want to write your task logic (time-consuming operation), such as synchronizing data, etc.
After the task is executed, you need to call jobFinished(JobParameters params, boolean needsRescheduled) to let the system know that the task has ended and the system can add the next task to the queue. If you do not call jobFinished(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 passed from the params of the onStartJob (JobParameters params) of JobService.needsRescheduledThe parameter is to let the system know whether the task should be executed repeatedly under the highest conditions. This boolean value is useful because it indicates how you handle situations where task execution fails due to other reasons, such as a failed network request call.
After creating the Handler instance, you can implement the onStartJob(JobParameters params) and onStopJob(JobParameters params) methods to control your tasks. You may have noticed that onStartJob(JobParameters params) returns true in the following code snippet. This is because you need to control your operations through the Handler instance.
This means that the Handler's handleMessage method may be executed longer than onStartJob(JobParameters params). Return true, you will let the system know that you will call it manuallyjobFinished(JobParameters params, boolean needsRescheduled)method.
@Override public boolean onStartJob(JobParameters params) { ( ( mJobHandler, 1, params ) ); return true; } @Override public boolean onStopJob(JobParameters params) { ( 1 ); return false; }
Once you have done the above work in the Java section, you need to add a service node to allow your application to bind and use this JobService.
<service android:name=".JobSchedulerService" android:permission=".BIND_JOB_SERVICE" />
2. Create a JobScheduler object
With the JobSchedulerService 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 initialize a JobScheduler object called mJobScheduler through getSystemService (Context.JOB_SCHEDULER_SERVICE ).
mJobScheduler = (JobScheduler) getSystemService( Context.JOB_SCHEDULER_SERVICE );
When you want to create a timed task, you can use it to build a JobInfo object and then pass it to your Service. Receive two parameters. The first parameter is the identifier of the task you want to run, and the second is the class name of the Service component.
builder = new ( 1, new ComponentName( getPackageName(), () ) );
This builder allows you to set a number of different options to control the execution of tasks. The following code snippet shows how to set up so that your task can run every three seconds.
( 3000 );
Other settings:
•setMinimumLatency(long minLatencyMillis):
This function allows you to set the delayed execution time of the task (in milliseconds). This function is incompatible with the setPeriodic(long time) method. If these two methods are called at the same time, an exception will be caused;
•setOverrideDeadline(long maxExecutionDelayMillis):
This method allows you to set the latest delay time for the task. If other conditions have not been met when the specified time is reached, your task will also be activated. Like setMinimumLatency(long time), this method will also be like setPeriodic(long time), calling these two methods at the same time will throw an exception.
•setPersisted(boolean isPersisted):
This method tells the system whether your task needs to continue to be executed after your device is restarted.
•setRequiredNetworkType(int networkType):
This method allows you to perform this task only when the specified network conditions are met. The default condition is JobInfo.NETWORK_TYPE_NONE, which means that this task will be executed regardless of network or not. Two other optional types, one is JobInfo.NETWORK_TYPE_ANY, which indicates that either network is required to make the task perform. The other is JobInfo.NETWORK_TYPE_UNMETERED, which means that the task will be executed only when the device is not a cellular network (such as when it is connected to WIFI).
•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 will only be started when the user is not using the device and has not been used for a period of time.
It should be noted that setRequiredNetworkType(int networkType), setRequiresCharging(boolean requireCharging) and setRequiresDeviceIdle(boolean requireIdle) may make your task unable to be executed unless the maximum delay time is set, so that your task will be executed if the condition is met. Once your preset condition is set, you can build a JobInfo object and send it to your JobScheduler through the code shown below.
if( ( () ) <= 0 ) { //If something goes wrong }
You may have noticed that this schedule method returns an integer. If the schedule method fails, it returns an error code less than 0. Otherwise it will have the ID we define in.
If your application wants to stop a task, you can call cancel(int jobId) of the JobScheduler object to implement it; if you want to cancel all tasks, you can call cancelAll() of the JobScheduler object to implement it.
();
By this point, you should now know how to use the JobScheduler API to perform batch tasks and background operations in your application.
in conclusion
In this article, you learned how to implement a JobService subclass that uses Handler objects to run background tasks, and you also learned how to use it to set up a JobService. After mastering these, you can reduce resource consumption while improving application efficiency.
More articles
For more excellent articles, please clickandroid-tech-frontier。
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.