0
点赞
收藏
分享

微信扫一扫

JobIntentService

Separes 2021-10-09 阅读 20
随笔

public class MyJobIntentServiceextends JobIntentService {

/**

    * 这个Service 唯一的id

*/

    static final int JOB_ID =10111;

    private StringTAG="MyJobIntentService";

    /**

* Convenience method for enqueuing work in to this service.

*/

    static void enqueueWork(Context context, Intent work) {

enqueueWork(context, MyJobIntentService.class, JOB_ID, work);

    }

@Override

    protected void onHandleWork( Intent intent) {

Log.i(TAG, "onHandleWork: "+intent.getStringExtra("url"));

        SystemClock.sleep(5000);

        Log.i(TAG, "onHandleWork: 任务执行完成");

    }

@Override

    public void onDestroy() {

super.onDestroy();

        Log.i(TAG, "onDestroy: ");

    }

}


在Activity中执行如下代码:

public void startJobService(View view) {

    Intent intent=new Intent();

    intent.putExtra("url","http://www.sina.com");

    MyJobIntentService.enqueueWork(getApplicationContext(),intent);

}

JobIntentService中有几个重要的参数:

WorkEnqueuer  :负责处理任务的传递
JobServiceEngine:任务服务引擎,负责任务的调度与执行
CompatWorkItem:负责执行过程中的时间调度

CommandProcessor:实质上是一个AsyncTask,真正的耗时操作是在这里执行的。在AsyncTask中的doInBackground()方法中,会调用JobIntentService 的未实现方法onHandleWork(),这个方法暴露给用户,进行业务需求上的耗时操作,完成任务后调用work.complete();,这个workComplete()的重写方法中会调用stopSelf(mStartId);,结束自身生命周期。


使用时需要注意两点:

(1)服务注册,本质上是一个service,所以需要注册,注册时需要加默认权限

<service android:name=".intentservice.MyJobIntentService"

    android:permission="android.permission.BIND_JOB_SERVICE"

    android:exported="true"/>

(2)权限申请:需要添加下面两个权限

<uses-permission android:name="android.permission.WAKE_LOCK"/>

<uses-permission android:name="android.permission.BIND_JOB_SERVICE"

    tools:ignore="ProtectedPermissions" />

举报

相关推荐

0 条评论