1. 程式人生 > >Android 5.0的排程作業JobScheduler

Android 5.0的排程作業JobScheduler

http://blog.csdn.net/cuiran/article/details/42805057

Android 5.0 提供了一個新的  API,它允許您通過為系統定義要在以後的某個時間或在指定的條件下(例如,當裝置在充電時)非同步執行的作業來優化電池壽命。

This is an API for scheduling various types of jobs against the framework that will be executed in your application's own process.

這是一個API排程框架,將在您的應用程式的程序中執行的工作


See  for more description of the types of jobs that can be run and how to construct them. You will construct these JobInfo objects and pass them to the JobScheduler with . When the criteria declared are met, the system will execute this job on your application's . You identify which JobService is meant to execute the logic for your job when you create the JobInfo with .

看到Jobinfo更多的描述型別的工作可以執行,以及如何構建。你可以構造這些JobInfo物件,並且使用schedule(JobInfo)在JobScheduler。

符合標準宣告系統將執行排程在你的應用程式Jobservice

The framework will be intelligent about when you receive your callbacks, and attempt to batch and defer them as much as possible. Typically if you don't specify a deadline on your job, it can be run at any moment depending on the current state of the JobScheduler's internal queue, however it might be deferred as long as until the next time the device is connected to a power source.


作業排程在下列情況下非常有用:

  • 應用具有您可以推遲的非面向使用者的工作。
  • 應用具有當插入裝置時您希望優先執行的工作。
  • 應用具有需要訪問網路或 Wi-Fi 連線的任務。
  • 應用具有您希望作為一個批次定期執行的許多工。

工作單元由一個  物件進行封裝。此物件指定了排程條件。官方的API如下

Public Methods
int Describe the kinds of special objects contained in this Parcelable's marshalled representation.
Bundle of extras which are returned to your application at execution time.
int getId() Unique job id associated with this class.
long The amount of time the JobScheduler will wait before rescheduling a failed job.
long Set to the interval between occurrences of this job.
long Set for a job that does not recur periodically, to specify a delay after which the job will be eligible for execution.
Name of the service endpoint that will be called back into by the JobScheduler.
boolean Track whether this job will repeat with a given period.
boolean Whether this job needs the device to be plugged in.
boolean Whether this job needs the device to be in an Idle maintenance window.
Returns a string containing a concise, human-readable description of this object.
void Flatten this object in to a Parcel.

使用  類配置排程的任務應當如何執行。您可以將任務排程為在特定的條件下執行,例如:

  • 當裝置充電時啟動
  • 當裝置連線到不限流量網路時啟動
  • 當裝置空閒時啟動
  • 在特定的截止期限之前或以最小的延遲完成

例如,您可以新增如下程式碼以在不限流量網路上執行您的任務:

<span class="typ" style="color: rgb(102, 0, 102);">JobInfo</span><span class="pln" style="color: rgb(0, 0, 0);"> uploadTask </span><span class="pun" style="color: rgb(102, 102, 0);">=</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="kwd" style="color: rgb(0, 0, 136);">new</span><span class="pln" style="color: rgb(0, 0, 0);"> </span><span class="typ" style="color: rgb(102, 0, 102);">JobInfo</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="typ" style="color: rgb(102, 0, 102);">Builder</span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="pln" style="color: rgb(0, 0, 0);">mJobId</span><span class="pun" style="color: rgb(102, 102, 0);">,</span><span class="pln" style="color: rgb(0, 0, 0);">
                                         mServiceComponent </span><span class="com">/* JobService component */</span><span class="pun" style="color: rgb(102, 102, 0);">)</span><span class="pln" style="color: rgb(0, 0, 0);">
        </span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">setRequiredNetworkCapabilities</span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="typ" style="color: rgb(102, 0, 102);">JobInfo</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="typ" style="color: rgb(102, 0, 102);">NetworkType</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">UNMETERED</span><span class="pun" style="color: rgb(102, 102, 0);">)</span><span class="pln" style="color: rgb(0, 0, 0);">
        </span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">build</span><span class="pun" style="color: rgb(102, 102, 0);">();</span><span class="pln" style="color: rgb(0, 0, 0);">
</span><span class="typ" style="color: rgb(102, 0, 102);">JobScheduler</span><span class="pln" style="color: rgb(0, 0, 0);"> jobScheduler </span><span class="pun" style="color: rgb(102, 102, 0);">=</span><span class="pln" style="color: rgb(0, 0, 0);">
        </span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="typ" style="color: rgb(102, 0, 102);">JobScheduler</span><span class="pun" style="color: rgb(102, 102, 0);">)</span><span class="pln" style="color: rgb(0, 0, 0);"> context</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">getSystemService</span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="typ" style="color: rgb(102, 0, 102);">Context</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">JOB_SCHEDULER_SERVICE</span><span class="pun" style="color: rgb(102, 102, 0);">);</span><span class="pln" style="color: rgb(0, 0, 0);">
jobScheduler</span><span class="pun" style="color: rgb(102, 102, 0);">.</span><span class="pln" style="color: rgb(0, 0, 0);">schedule</span><span class="pun" style="color: rgb(102, 102, 0);">(</span><span class="pln" style="color: rgb(0, 0, 0);">uploadTask</span><span class="pun" style="color: rgb(102, 102, 0);">);</span>

如果裝置具有穩定的電源(也就是說,它已插入了 2 分鐘以上並且電池處於健康水平),則系統將執行任何已就緒可執行的已排程作業,即使作業的截止期限尚未到期也是如此。

Entry point for the callback from the .

This is the base class that handles asynchronous requests that were previously scheduled. You are responsible for overriding , which is where you will implement your job logic.

This service executes each incoming job on a  running on your application's main thread. This means that you must offload your execution logic to another thread/handler/ of your choosing. Not doing so will result in blocking any future callbacks from the JobManager - specifically , which is meant to inform you that the scheduling requirements are no longer being met.

所提供的方法如下

final void Callback to inform the JobManager you've finished executing.   當完成執行後,通知排程管理器
abstract boolean Override this method with the callback logic for your job.
abstract boolean This method is called if the system has determined that you must stop execution of your job even before you've had a chance to call .

下面可以看一下官方給出的一個sample

執行效果如下


Activity如下

  1. /* 
  2.  * Copyright 2013 The Android Open Source Project 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */
  16. package com.example.android.jobscheduler;  
  17. import android.app.Activity;  
  18. import android.app.job.JobInfo;  
  19. import android.app.job.JobParameters;  
  20. import android.app.job.JobScheduler;  
  21. import android.content.ComponentName;  
  22. import android.content.Context;  
  23. import android.content.Intent;  
  24. import android.content.res.Resources;  
  25. import android.os.Bundle;  
  26. import android.os.Handler;  
  27. import android.os.Message;  
  28. import android.os.Messenger;  
  29. import android.text.TextUtils;  
  30. import android.view.View;  
  31. import android.widget.CheckBox;  
  32. import android.widget.EditText;  
  33. import android.widget.RadioButton;  
  34. import android.widget.TextView;  
  35. import android.widget.Toast;  
  36. import com.example.android.jobscheduler.service.TestJobService;  
  37. publicclass MainActivity extends Activity {  
  38.     privatestaticfinal String TAG = "MainActivity";  
  39.     publicstaticfinalint MSG_UNCOLOUR_START = 0;  
  40.     publicstaticfinalint MSG_UNCOLOUR_STOP = 1;  
  41.     publicstaticfinalint MSG_SERVICE_OBJ = 2;  
  42.     @Override
  43.     publicvoid onCreate(Bundle savedInstanceState) {  
  44.         super.onCreate(savedInstanceState);  
  45.         setContentView(R.layout.sample_main);  
  46.         Resources res = getResources();  
  47.         defaultColor = res.getColor(R.color.none_received);  
  48.         startJobColor = res.getColor(R.color.start_received);  
  49.         stopJobColor = res.getColor(R.color.stop_received);  
  50.         // Set up UI.
  51.         mShowStartView = (TextView) findViewById(R.id.onstart_textview);  
  52.         mShowStopView = (TextView) findViewById(R.id.onstop_textview);  
  53.         mParamsTextView = (TextView) findViewById(R.id.task_params);  
  54.         mDelayEditText = (EditText) findViewById(R.id.delay_time);  
  55.         mDeadlineEditText = (EditText) findViewById(R.id.deadline_time);  
  56.         mWiFiConnectivityRadioButton = (RadioButton) findViewById(R.id.checkbox_unmetered);  
  57.         mAnyConnectivityRadioButton = (RadioButton) findViewById(R.id.checkbox_any);  
  58.         mRequiresChargingCheckBox = (CheckBox) findViewById(R.id.checkbox_charging);  
  59.         mRequiresIdleCheckbox = (CheckBox) findViewById(R.id.checkbox_idle);  
  60.         mServiceComponent = new ComponentName(this, TestJobService.class);  
  61.         // Start service and provide it a way to communicate with us.
  62.         Intent startServiceIntent = new Intent(this, TestJobService.class);  
  63.         startServiceIntent.putExtra("messenger"new Messenger(mHandler));  
  64.         startService(startServiceIntent);  
  65.     }  
  66.     // UI fields.
  67.     int defaultColor;  
  68.     int startJobColor;