How to use jobscheduler in Android 5.0

Using jobscheduler in Android 5.0

• original link: using the job scheduler 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 tasks that execute in the background when certain conditions are met.

introduce

In Android development, there are some scenarios: 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 connected to the power adapter or WiFi. Fortunately, in API 21 (Android 5.0, lollipop), Google provides a new component called jobscheduler API to deal with such scenarios.

When a series of preset conditions are met, the jobscheduler API performs an operation for your application. Unlike the alarm manager, the execution time is uncertain. In addition, the jobscheduler API allows multiple tasks to be performed simultaneously. This allows your application to perform certain specified tasks without considering the battery consumption caused by timing control.

In this article, you will learn more about the jobscheduler API and the jobservice used to run a simple background task in your application. The code shown in this article can be found in GitHub.

1. Create job service

First of all, you need to create an Android project with a minimum API of 21. Therefore, jobscheduler was added to Android only in the latest version. At the time of writing this article, it had no compatible library support.

Suppose you are using Android studio. After you click the finish button to create a 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 named jobschedulerservice that inherits from jobservice. This class must implement two methods: onstartjob (jobparameters params) and onstopjob (jobparameters params);

When the task starts, the onstartjob (jobparameters params) method will be executed because it 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, the system assumes that the task is about to be executed, and the burden of executing the task falls on you. When the task is completed, you need to call jobfinished (jobparameters params, Boolean needsrescheduled) to notify the system.

When the system receives a cancellation request, the system will call onstopjob (jobparameters params) method to cancel the task waiting to be executed. A very important point is that if onstartjob (jobparameters params) returns false, the system assumes that there are no running tasks when receiving a cancellation request. In other words, onstopjob (jobparameters params) is not called in this case.

It should be noted that this job service runs on your main thread, which means that you need to use sub threads, handlers, or an asynchronous task to run time-consuming operations to prevent blocking the main thread. Because multithreading technology is beyond the scope of this article, let's simply implement a handler to perform the tasks defined in jobscheduler service.

In the handler, you need to implement the handlemessage (message MSG) method to handle your task logic. In this example, we try to keep the example simple, so we only display a toast in the handlemessage (message MSG), where you need to write your task logic (time-consuming operations), such as synchronizing data.

After the task is executed, you need to call jobfinished (jobparameters params, Boolean needs rescheduled) 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 be executed only once, and other tasks in the application will not be executed.

The params parameter of the two parameters of jobfinished (jobparameters params, Boolean needsrescheduled) is passed from the params of onstartjob (jobparameters params) of jobservice. The needsrescheduled parameter lets the system know whether the task should be repeated under the most favorable conditions. This Boolean value is very useful because it indicates how you deal with the failure of task execution due to other reasons, such as a failed network request call.

After creating the handler instance, you can implement 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 operation through the handler instance,

This means that the handler's handlemessage method may take longer to execute than onstartjob (jobparameters params). If true is returned, you will let the system know that you will manually call the jobfinished (jobparameters params, Boolean needsrescheduled) method.

Once you have done the above work in the Java part, you need to add a service node to androidmanifest.xml so that your application has the permission to bind and use this jobservice.

2. Create a jobscheduler object

With the jobscheduler service built, we can start to study how your application interacts with the jobscheduler API. The first thing to do is to create a jobscheduler object. In the mainactivity of the example code, we initialize a jobscheduler object called mjobscheduler through getsystemservice (context. Job_scheduler_service).

When you want to create a scheduled task, you can use jobinfo. Builder to build a jobinfo object and 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 is the class name of the service component.

This Builder allows you to set many different options to control the execution of tasks. The following code snippet shows how to set it so that your task can run every three seconds.

Other setting methods:

•setMinimumLatency(long minLatencyMillis):

This function allows you to set the delayed execution time of a 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 of the task. If other conditions are not met by the specified time, your task will also be started. Like setminimumlatency (long time), this method will be the same as 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 will continue 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 performed whether there is a network or not. The other two optional types are jobinfo.network_ TYPE_ Any, which indicates that any kind of network is required to make the task executable. 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 WiFi is connected).

•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 be started only when the user is not using the device for a period of time.

It should be noted that the setrequirednetworktype (int networktype), setrequiredcharging (Boolean requiredcharging) and setrequireddeviceidle (Boolean requiredidle) methods may make your task impossible to execute, unless you call setoverridedeadline (long time) to set the maximum delay time, so that your task will be executed when the conditions are met. Once your preset conditions are set, you can build a jobinfo object and send it to your jobscheduler through the code shown below.

You may have noticed that the schedule method returns an integer. If the schedule method fails, it returns an error code less than 0. Otherwise, it will the identity ID we defined in jobinfo. Builder.

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.

By now, you should know how to use the jobscheduler API to perform batch tasks and background operations in your application.

conclusion

In this article, you learned how to implement a subclass of jobservice that uses the handler object to run background tasks, and you also learned how to use jobinfo.builder to set jobservice. After mastering these, you can reduce resource consumption and improve application efficiency at the same time.

More articles

For more excellent articles, please hit Android tech frontier.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>