IntentService
- IntentService 内部维护一个HanlderThread和一个Handler。实际是维护了一个单线程的任务队列。通过IntentService启动的任务都是按顺序依次执行的,并且是在子线程中执行。
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
}
首次启动IntentService时 会调用onCreate()创建HandlerThread、mServiceLooper和mServiceHandler。onStartCommand 将任务添加到任务队列中。任务从任务队列中取出 会在handleMessage中交给onHandleIntent()方法来执行。
当所有的任务都执行完毕后,IntentService会自己销毁。
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
IntentService适用的场景:
当一个任务有很多小任务组成,并且这些小任务必须按一定顺序执行,而且这些任务可能会比较耗时。
使用IntentService
使用IntentService 只需要继承IntentService,
- 复写onHandleIntent方法
- 同时创建一个缺省的构造方法
HandleTaskService.java
public class HandleTaskService extends IntentService {
private static final String TAG = HandleTaskService.class.getSimpleName();
/**
* 单线程 任务队列中,需要处理任务的方法(子线程执行)
* @param intent
*/
@Override
protected void onHandleIntent(Intent intent) {
String op = intent.getStringExtra("op");
int param = intent.getIntExtra("param",-1);
Log.d(TAG,"onHandleIntent - op:"+op+"_"+param+",Thread:"+Thread.currentThread().getName());
try {
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}finally {
}
Log.d(TAG,"onHandleIntent task "+op+"_"+param+",finish"+",Thread:"+Thread.currentThread().getName());
}
/**
* 无参构造方法
*/
public HandleTaskService(){
super("HandleTaskService");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"onCreage()");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy()");
}
}
manifest.xml
<service
android:name=".HandleTaskService"
/>
调用IntentService:
Intent intent = new Intent(this,HandleTaskService.class);
intent.putExtra("op","delete");
intent.putExtra("param",i++);
startService(intent);
参考链接:
https://www.jianshu.com/p/945c97556964
https://blog.csdn.net/smbroe/article/details/45009721
github:
https://github.com/feifei-123/MyExampleCode
参看工程中intentserviceexample子模块