Using Jobscheduler in Android 5.0

Source: Internet
Author: User

Using Jobscheduler in Android 5.0
  • Original link: Using-the-jobscheduler-api-on-android-lollipop
  • Translator: Mr.simple
  • Reviewer: 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 perform in the background when certain conditions are met.

Introduced

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 plugged into a power adapter or connected to WiFi. Fortunately, in API (Android 5.0, or Lollipop), Google provides a new component called the Jobscheduler API to handle such scenarios.

The Jobscheduler API performs an action for your app when a series of preset conditions are met. Unlike Alarmmanager, this execution time is uncertain. In addition, the Jobscheduler API allows multiple tasks to be performed simultaneously. This allows your app to perform some specified tasks without considering the battery consumption caused by timing control.

In this article, you'll learn more about the Jobscheduler API and the Jobservice for running a simple background task in your app, and the code shown in this article can be found on GitHub.

1. Create a job Service

First of all, you need to create an Android project with a minimum API of 21, so Jobscheduler is the latest version to add to Android, and it doesn't have a compatible library when writing this post.

The

assumes that you are using Android Studio, and when you click the Finish button to create the project, you will get a "Hello World" application skeleton. The first step you need to make is to create a new Java class. For the sake of simplicity, let's create a class that inherits from Jobservice and named Jobschedulerservice, which must implement two methods, onstartjob (jobparameters params), respectively. and onstopjob (jobparameters params) ;

public  class  jobschedulerservice  extends  jobservice  {     @Override  public  boolean  onstartjob  (Jobparameters params)    {return  false ; }  @Override  public  boolean  onstopjob  (jobparameters params) {return  false ; }}

The method executes when the task starts onStartJob(JobParameters params) , because it is used by the system to trigger a task that has already 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 finished executing when the method returns. If the return value is true, then the system assumes that the task is about to be executed, and the burden of performing the task falls on your shoulders. You need to call to notify the system when the task has finished executing jobFinished(JobParameters params, boolean needsRescheduled) .

When the system receives a cancellation request, the system calls the onStopJob(JobParameters params) method to cancel the task that is waiting to be executed. It is important that if you onStartJob(JobParameters params) return FALSE, the system assumes that there are no running tasks when a cancellation request is received. In other words, onStopJob(JobParameters params) it will not be called in this case.

Note 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 a time-consuming operation to prevent the main thread from blocking. Because multithreaded technology is beyond the scope of our article, let's simply implement a handlder to perform the tasks we define in Jobschedulerservice.

privatenewnew Handler.Callback() {    @Override    publicbooleanhandleMessage( Message msg ) {        Toast.makeText( getApplicationContext(),             "JobService task running", Toast.LENGTH_SHORT )            .show();        false );        returntrue;    }} );

In handler, you need to implement handleMessage(Message msg) a method to handle your task logic. In this example, we try to ensure that the example is simple, so we only handleMessage(Message msg) show a toast in, here is where you write your task logic (time consuming operation), such as synchronizing data.

When the task is finished, 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 app will not be executed.

jobFinished(JobParameters params, boolean needsRescheduled)The params parameter in the two parameters is passed from the Jobservice onStartJob(JobParameters params) params, and the needsrescheduled parameter is to let the system know whether the task should be repeated in the most condition. This boolean value is useful because it indicates how you handle situations where a task execution failed for other reasons, such as a failed network request call.

Once you have created the handler instance, you can implement onStartJob(JobParameters params) and onStopJob(JobParameters params) approach to control your task. You may have noticed that true is returned in the following code fragment onStartJob(JobParameters params) . This is because you want to control your operation through the handler instance,

这意味着Handler的handleMessage方法的执行时间可能比Onstartjob (jobparameters params) 更长。 returns True and you will let the system know that you will invoke the jobFinished(JobParameters params, boolean needsRescheduled) method manually.

@OverridepublicbooleanonStartJob(JobParameters params) {    1, params ) );    returntrue;}@OverridepublicbooleanonStopJob(JobParameters params) {    1 );    returnfalse;}

Once you have done this in the Java section, you need to add a service node to Androidmanifest.xml to have your app bind and use this jobservice permission.

<service android:name=".JobSchedulerService"    android:permission="android.permission.BIND_JOB_SERVICE" />
2. Create a Jobscheduler object

As Jobschedulerservice is built, we can begin to examine how your app interacts with the Jobscheduler API. The first thing to do is you need to create a Jobscheduler object, in the mainactivity of the instance code we getSystemService( Context.JOB_SCHEDULER_SERVICE ) initialize a Jobscheduler object called Mjobscheduler.

mJobScheduler = (JobScheduler)     getSystemService( Context.JOB_SCHEDULER_SERVICE );

When you want to create a timed task, you can use it JobInfo.Builder to build a Jobinfo object and then pass it on 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.

new1,        new ComponentName( getPackageName(),             JobSchedulerService.class.getName() ) );

This builder allows you to set a number of different options to control the execution of the task. The following code snippet shows how to set up so that your task can run every three seconds.

3000 );

Other Setup methods:

    • setminimumlatency (Long Minlatencymillis): This function allows you to set the delay execution time (in milliseconds) of the task, which is associated with the Setperiodic (long time) The method is incompatible and will cause an exception if both methods are called at the same time;
    • setoverridedeadline (Long Maxexecutiondelaymillis):
      This method allows you to set the latest delay time for a task. If other conditions are not met at the specified time, your task will be activated. As with setminimumlatency (long time) , this method is also associated with Setperiodic (long time) , and calling both methods throws an exception.
    • setpersisted (boolean ispersisted):
      This method tells the system whether your task will continue to execute after your device restarts.
    • setrequirednetworktype (int networktype):
      This method allows you to perform this task only if the specified network conditions are met. The default condition is Jobinfo.network_type_none, which means that the task will be executed regardless of whether or not there is a network. The other two optional types, one is 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 is not executed when the device is not a cellular network, such as when it is connected to a WiFi connection.
    • setrequirescharging (boolean requirescharging):
      This method tells your app that the task will only be executed if the device is charging.
    • Setrequiresdeviceidle (boolean requiresdeviceidle):
      This method tells you that the task will only start if the user is not using the device and has not been used for some time.

It is important to note setRequiredNetworkType(int networkType) that several of the setRequiresCharging(boolean requireCharging) setRequiresDeviceIdle(boolean requireIdle) methods may make your task impossible to execute unless the call setOverrideDeadline(long time) sets the maximum delay time so that your task will be executed if the condition is met. Once you have provisioned the conditions set, you can build a Jobinfo object and then send it to your jobscheduler using the code shown below.

if0 ) {    //If something goes wrong}

You may have noticed that this schedule method returns an integer type. If the schedule method fails, it returns an error code that is less than 0. Otherwise it will be the identity ID that we defined in Jobinfo.builder.

If your application wants to stop a task, you can invoke the Jobscheduler object cancel(int jobId) to implement it, and if you want to cancel all the tasks, you can invoke the Jobscheduler object cancelAll() .

mJobScheduler.cancelAll();

Here, you should now know how to use the Jobscheduler API in your app to perform bulk 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 you learned how to use Jobinfo.builder to set up Jobservice. With this in hand, you can increase the efficiency of your application while reducing resource consumption.

More Articles

For more excellent articles, bash android-tech-frontier.

Using Jobscheduler in Android 5.0

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.