1. 程式人生 > >【學習筆記】Google JobScheduler Demo的學習與運用

【學習筆記】Google JobScheduler Demo的學習與運用

官方 DEMO

路徑如下

sdk\sources\android-22\com\android\demo\jobSchedulerApp\

Demo 需求

JobShedule的出發點是提供省電場景給使用者進行任務完成,目前主要場景如下
1.網路資料場景
2.充電場景
3.idle待機場景
4.固定週期場景

接下來我們已
充電下且網路為連線時的場景為例進行JobShedule的使用說明。

Demo中的原始碼都是Google SDK自帶的

核心設定引數程式碼如下

        // 設定最小的延遲時間
        builder.setMinimumLatency(1
*1000); // 設定最大的延遲時間,一旦設定了這個屬性,不管其他條件怎麼樣,jobinfo到了時間就一定會執行。 builder.setOverrideDeadline(5*1000); // 設定在什麼樣的網路下啟動jobinfo builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED); // 設定裝置需要在空閒的時候,是否啟動job builder.setRequiresDeviceIdle(false); // 設定是否充電情況下排程
builder.setRequiresCharging(true);

備註:上述的關係是與的關係,不是或的關係

場景條件達成回撥介面如下


public class MyJobSchedulerService extends JobService{

    /**
     * 滿足Job預設定條件下回調 
     */
    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Log.d(Constant.TAG, "onStartJob: " + jobParameters.getJobId());
    }

    /**
     * 1.被CancleAll的時候回撥
     * 2.不滿足預設定條件的情況下回調
     */
@Override public boolean onStopJob(JobParameters jobParameters) { } }

重要許可權

    <service android:name=".service.MyJobSchedulerService"
        android:permission="android.permission.BIND_JOB_SERVICE"/>
    /**
     * Job services must be protected with this permission:
     *
     * <pre class="prettyprint">
     *     &#60;service android:name="MyJobService"
     *              android:permission="android.permission.BIND_JOB_SERVICE" &#62;
     *         ...
     *     &#60;/service&#62;
     * </pre>
     *
     * <p>If a job service is declared in the manifest but not protected with this
     * permission, that service will be ignored by the OS.
     */
    public static final String PERMISSION_BIND =
            "android.permission.BIND_JOB_SERVICE";

JobScheduler引數設定指令

public void scheduleJob(View v) {
        if (!ensureJobSchedulerService()) {
            return;
        }

        JobInfo.Builder builder = new JobInfo.Builder(kJobId++, mServiceComponent);
        /**
         * Specify that this job should be delayed by the provided amount of time.
         * Because it doesn't make sense setting this property on a periodic job, doing so will
         * throw an {@link java.lang.IllegalArgumentException} when
         * {@link android.app.job.JobInfo.Builder#build()} is called.
         * @param minLatencyMillis Milliseconds before which this job will not be considered for
         *                         execution.
         */
        // 設定最小的延遲時間
        // builder.setMinimumLatency(1*1000);
        /**
         * Set deadline which is the maximum scheduling latency. The job will be run by this
         * deadline even if other requirements are not met. Because it doesn't make sense setting
         * this property on a periodic job, doing so will throw an
         * {@link java.lang.IllegalArgumentException} when
         * {@link android.app.job.JobInfo.Builder#build()} is called.
         */
        // 設定最大的延遲時間,一旦設定了這個屬性,不管其他條件怎麼樣,jobinfo到了時間就一定會執行。
        // builder.setOverrideDeadline(5*1000);
        /** Default. 任意網路都可以*/
        // public static final int NETWORK_TYPE_NONE = 0;
        /** This job requires network connectivity. 任意網路都可以*/
        // public static final int NETWORK_TYPE_ANY = 1;
        /** This job requires network connectivity that is unmetered. 無線網路接入*/
        // public static final int NETWORK_TYPE_UNMETERED = 2;
        /** This job requires network connectivity that is not roaming. 非漫遊*/
        // public static final int NETWORK_TYPE_NOT_ROAMING = 3;
        /** This job requires metered connectivity such as most cellular data networks. 移動資料網路 */
        // public static final int NETWORK_TYPE_METERED = 4;
        // 設定在什麼樣的網路下啟動jobinfo
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);

        /**
         * Specify that to run, the job needs the device to be in idle mode. This defaults to
         * false.
         * <p>Idle mode is a loose definition provided by the system, which means that the device
         * is not in use, and has not been in use for some time. As such, it is a good time to
         * perform resource heavy jobs. Bear in mind that battery usage will still be attributed
         * to your application, and surfaced to the user in battery stats.</p>
         * @param requiresDeviceIdle Whether or not the device need be within an idle maintenance
         *                           window.
         */
        // 設定裝置需要在空閒的時候,是否啟動job
        builder.setRequiresDeviceIdle(false);

        /**
         * Specify that to run this job, the device needs to be plugged in. This defaults to
         * false.
         * @param requiresCharging Whether or not the device is plugged in.
         */
        // 設定是否充電情況下排程
        builder.setRequiresCharging(true);
        /**
         * Set whether or not to persist this job across device reboots.
         *
         * @param isPersisted True to indicate that the job will be written to
         *            disk and loaded at boot.
         */
        // 設定是否重啟後繼續排程,注意設定true是需要新增重啟許可權
        builder.setPersisted(false);

        /**
         * 我設定了充電下且網路連線時才觸發onJobStart()的條件
         * 注意:上述的條件是與的關係,不是或
         */
        Log.d(Constant.TAG, "設定充電下且網路連線的條件");
        tv_info.setText("設定充電下且網路連線的條件");
        myJobSchedulerService.schedulejob(builder.build());
    }

結束Job任務指令

結束所有JOB

    /**
     * 殺死在這個包裡註冊的所有的jobinfo
     * @param v
     */
    public void cancelAllJobs(View v) {
        JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

        /**
         * Cancel all jobs that have been registered with the JobScheduler by this package.
         *
         * 備註:這裡會回撥onStopJob();
         */
        tm.cancelAll();

        tv_info.setText("殺死在這個包裡註冊的所有的jobinfo");
    }

結束指定JOB

    public void callJobFinished() {

        if (mJobParametersMap.size() == 0) {
            return ;
        }

        JobParameters params = mJobParametersMap.valueAt(0);
        if (params == null) {
            return; 
        } else {
            /**
             * Call this to inform the JobManager you've finished executing. This can be called from any
             * thread, as it will ultimately be run on your application's main thread. When the system
             * receives this message it will release the wakelock being held.
             * <p>
             *     You can specify post-execution behaviour to the scheduler here with
             *     <code>needsReschedule </code>. This will apply a back-off timer to your job based on
             *     the default, or what was set with
             *     {@link android.app.job.JobInfo.Builder#setBackoffCriteria(long, int)}. The original
             *     requirements are always honoured even for a backed-off job. Note that a job running in
             *     idle mode will not be backed-off. Instead what will happen is the job will be re-added
             *     to the queue and re-executed within a future idle maintenance window.
             * </p>
             *
             * @param params Parameters specifying system-provided info about this job, this was given to
             *               your application in {@link #onStartJob(JobParameters)}.
             * @param needsReschedule True if this job should be rescheduled according to the back-off
             *                        criteria specified at schedule-time. False otherwise.
             */

            /**
             * 告訴JobManager 已經完成了工作,如果第二個引數為false,就是不需要重試這個jobinfo,
             *   第二個引數為true,相當於告訴系統任務失敗,需要重試,而且與要遵守之前的jobinfo.
             *   
             * 備註:這裡不會回撥onStopJob();
            */
            jobFinished(params, false);

            String result = "callJobFinished getJobId = " + params.getJobId();
            Log.d(Constant.TAG, result);
            if (null != mainActivity) {
                mainActivity.onReceivedJobFinished(result);
            }

            mJobParametersMap.removeAt(0);
        }
    }

Job回撥事件

預設定條件滿足事件回撥

    /**
     *  滿足Job預設定條件下回調 
     */
    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Log.d(Constant.TAG, "當前滿足預設定條件,故觸發 onStartJob: " + jobParameters.getJobId());

        mCurrentId ++;
        mJobParametersMap.put(mCurrentId, jobParameters);

        if (null != mainActivity) {
            mainActivity.onReceivedStartJob(jobParameters);
        }
        return true;
    }

預設定條件不滿足事件回撥

    /**
     * 1.被CancleAll的時候回撥
     * 2.不滿足預設定條件的情況下回調
     */
    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Log.d(Constant.TAG, "不滿足預設定條件, onStopJob : " + jobParameters.getJobId());

        int id = mJobParametersMap.indexOfValue(jobParameters);
        mJobParametersMap.remove(id);

        if (null != mainActivity) {
            mainActivity.onReceivedStopJob(jobParameters);
        }
        return false;
    }

結語

個人任務Job本質提供合適的省電場景,讓應用執行一些費時且優先順序不是很高的事情,比如備份,資料上傳等等,當然不建議利用這個特性進行保活,即利用該機制完成應用的頻繁啟動,這樣就違背Google的初衷了

Demo下載

這裡寫圖片描述

相關推薦

學習筆記Google JobScheduler Demo學習運用

官方 DEMO 路徑如下 sdk\sources\android-22\com\android\demo\jobSchedulerApp\ Demo 需求 JobShedule的出發點是提供省電場景給使用者進行任務完成,目前主要場景如下 1.網路資

學習筆記FreeMarker 之於ServletStuts2的應用

patch warnings ftl 4.0 type shm .html enter src FreeMarker應用在Servlet(0配置web.xml形式): 準備環境: tomcat7、eclipse最新版、jdk1.8、freemarker v2.3.20.ja

Python學習筆記Coursera之PY4E學習筆記——File

color 學習筆記 函數 read mod rom stephen 內容 filename 1、打開文件 使用handle=open(filename,mode)打開文件。這一函數將會返回一個handle(應該翻譯為“柄”吧)用來操控文件,參數filename是一個字符串

學習筆記 狄利克雷莫比烏斯

數論 學習筆記 卷積 加法 結果 整數 class 知識 rac Ahead 10.9.2018 前置知識 數論函數 指一個正整數集對一個數集的映射 可以看成 N+->R 加法 若函數 \(f(x) + g(x) = h(x)\) 那麽 \(h(x) = \sum_{

OpenCV學習筆記之影象輪廓特徵影象的矩

轉載: https://blog.csdn.net/zhu_hongji/article/details/81699736   一、影象的輪廓(Contours of Image)        輪廓可以說是一個很好的影象目標的

R語言學習筆記RGraphviz包的安裝載入方法

      最近學習一個演算法,是用R語言實現的,其中需要用到RGraphviz,我原先想按照以前安裝包的方法:在映象中找到就可以直接點選、安裝該包。可是我找遍了不同地區的一些映象,都找不到我想要安裝的包。所以我查詢資料,試了很多方法,最後成功了

日常學習筆記2019/1/3(Log4jweb安全)

Log4j日誌學習 log4j日誌輸出使用教程 https://www.cnblogs.com/sky230/p/5759831.html Spring+SpringMVC+MyBatis+easyUI整合優化篇(二)Log4j講解與整合 https://www.cnblogs.

ML學習筆記3:機器學習中的數學基礎3(特徵值,特徵向量,認識SVD)

矩陣乘以向量的幾何意義 實際上也就是 所以,它還可以寫成 那麼把原來的矩陣按照列檢視來看,也就是 而[x]和[y]作為1x1的矩陣,在剛剛那個式子裡可以看成一個標量,也就變成了 所以矩陣乘以一個列向量,可以看成把這個列向量的每一個分

Hibernate學習筆記Session清空快取清理快取

1. 清空快取     當呼叫session.evict(customer); 或者session.clear(); 或者session.close()方法時,Session的快取被清空。 2. 清理快取     Session具有一個快取,位於快取中的物件處於持久化狀態

Unity學習筆記Unity設定單位長度畫素間的對應關係

在製作Roguelike遊戲時,需要隨機生成tiled地圖,此時需要將Unity的一個單位與Sprite的畫素相對應,方法如下: 1、單擊資原始檔夾下的Sprite; 2、在Inspector下的Pixel Per Unit屬性下填入一單位長度所對應的畫素數。

Android學習筆記屬性動畫基礎學習筆記

屬性動畫 屬性動畫系統是一個具有魯棒性的框架,允許你幾乎讓一切都動起來。你能夠定義一個動畫來隨著時間改變任何物件的任何屬性,無視該物件是否是畫在在螢幕上的。屬性動畫在指定的時間內改變屬性值(某個物件的某個屬性)。為了讓目標動起來,需要特別指明所要運動的目標的屬性,例如目標在螢幕上的位置,運動的時間長

ML學習筆記5:機器學習中的數學基礎5(張量,哈達瑪積,生成子空間,超平面,範數)

向量/矩陣/張量 向量 向量可以表示成一維陣列,每個分量可以理解為向量所表示的點在空間中座標的分量。 矩陣 矩陣可以表示成二維陣列,上節理解了矩陣可以理解為線性對映在特定基下的一種定量描述。 張量 張量可以表示成任意維的陣列,張量是向量概

Linux學習筆記Chapter 7 Linux檔案目錄管理_筆記

【記錄整理自《鳥哥的Linux私房菜》】 一、目錄與路徑 1.相對路徑與絕對路徑 1)絕對路徑:路徑的寫法一定由根目錄(/)寫起,比如/usr/share/doc這個目錄 a)用途:正確度比較

ARM學習筆記實驗三:S3C2440A記憶體SDRAM連線實驗

前文講到了儲存控制器對外引出了8根片選訊號線,分別對應8個BANK,每個BANK的地址空間大小為128MB,共計1GB的物理定址空間 在8個BANK中,BANK0佔用匯流排地址0x00000000~0x07FFFFFF,而CPU在上電後會從匯流排地址0x00000000讀取

c++學習筆記深入解析淺拷貝深拷貝

測試環境:vs2013 什麼是淺拷貝 也稱位拷貝,編譯器只是將物件中的值拷貝過來,如果物件中管理資源,最後就會導致多個物件共享同一份資源,當一個物件銷燬時就會將該資源釋放掉,而此時另一些物件不知道該資源已經被釋放,以為還有效,所以當繼續對資源進行操作時

論文筆記《基於深度學習的中文命名實體識別研究》閱讀筆記

作者及其單位:北京郵電大學,張俊遙,2019年6月,碩士論文 摘要 實驗資料:來源於網路公開的新聞文字資料;用隨機欠取樣和過取樣的方法解決分類不均衡問題;使用BIO格式的標籤識別5類命名實體,標註11種標籤。 學習模型:基於RNN-CRF框架,提出Bi-GRU-Attention模型;基於改進的ELMo可

讀書筆記《Linux核心設計實現》程序管理程序排程

大學跟老師做嵌入式專案,寫過I2C的裝置驅動,但對Linux核心的瞭解也僅限於此。Android系統許多導致root的漏洞都是核心中的,研究起來很有趣,但看相關的分析文章總感覺隔著一層窗戶紙,不能完全理會。所以打算系統的學習一下Linux核心。買了兩本書《Linux核心設計與實現(第3版)》和《深入理解Lin

JavaScript學習筆記調用google搜索

alt href blog ddl ear input arch -c html <html> <form method=get action="http://www.google.com/search"> <a

jwt學習筆記--demo練習

第一步、匯入maven座標 <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version

ML學習筆記樸素貝葉斯演算法的demo(機器學習實戰例子)

礙於這學期課程的緊迫,現在需要儘快從課本上掌握一些ML演算法,我本不想經過danger zone,現在看來卻只能儘快進入danger zone,數學理論上的缺陷只能後面找時間彌補了。 如果你在讀這篇文章,希望你不要走像我一樣的道路,此舉實在是出於無奈,儘量不要去做一個心