【原創(chuàng)】JobIntentService使用

最近App出現(xiàn)了一個線上crash,日志如下:

java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.xxx.xx/.core.service.NotifyJobService }: app is in background uid UidRecord{6dd5849 u0a172 TPSL idle change:idle|cached procs:1 seq(0,0,0)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1628)
at android.app.ContextImpl.startService(ContextImpl.java:1569)
at android.content.ContextWrapper.startService(ContextWrapper.java:675)
at com.xxx.xx.application.MainApp.onCreate(Unknown Source:385)
at com.baidu.protect.A.a(Native Method)
at com.baidu.protect.StubApplication.onCreate(StubApplication.java:296)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1154)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6273) ... 8 more

具體原因是因為從Android 8.0開始禁止應(yīng)用在后臺運行時創(chuàng)建Service。

網(wǎng)上的解決方案大致有以下幾種:
?1.通過Context.startForegroundService()方式啟動一個前臺Service,前臺Service的啟動沒有受到限制。
?2.集成Google Firebase Messaging。
?3.使用JobIntentService。

?其中方案一最簡單,并且是國內(nèi)大多數(shù)blog博主推薦的解決方案,但是考慮到項目需求,啟動一個前臺Service實在是不合適。
?方案二、三普遍被國外開發(fā)者所采用,但是Google Firebase畢竟在國內(nèi)使用會有諸多限制,于是個人決定采用方案三來解決。

JobIntentService

JobIntentService是Android 8.0 新加入的類,它也是繼承自Service,根據(jù)官方的解釋:

Helper for processing work that has been enqueued for a job/service. When running on Android O or later, the work will be dispatched as a job via JobScheduler.enqueue. When running on older versions of the platform, it will use Context.startService.

?大致是說JobIntentService用于執(zhí)行加入到隊列中的任務(wù)。對Android 8.0及以上的系統(tǒng),JobIntentService的任務(wù)將被分發(fā)到JobScheduler.enqueue執(zhí)行,對于8.0以下的系統(tǒng),任務(wù)仍舊會使用Context.startService執(zhí)行。

?JobIntentService具體使用起來非常簡單,它已經(jīng)封裝了大量的內(nèi)部邏輯,只需要調(diào)用enqueue()就可以了。

使用示例:
1.在Manifest中聲名Permission:
<uses-permission android:name="android.permission.WAKE_LOCK" />
2.在Manifest中聲名Service:
<service android:name=".YourService" android:permission="android.permission.BIND_JOB_SERVICE" />
3.實現(xiàn)JobIntentService類:

public class YourService extends JobIntentService {

    public static final int JOB_ID = 1;

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, YourService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        // 具體邏輯
    }

}

4.需要調(diào)用的地方:
YourService.enqueueWork(context, new Intent());

?我們可以看到,JobIntentService的使用相比JobService簡化了很多,開發(fā)者甚至不需要關(guān)心JobIntentService的生命周期,不需要startService()方法,也就避免了開頭中的crash問題,通過靜態(tài)方法就可以啟動,可以說是非常友好了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容