IntentService
Service 的一个子类,该类会创建一个线程来处理所有的 start 请求,一次处 理一个。如果你不需要你的 service 同时处理多个请求,这个类是你的最佳 选择。你只需实现 onHandleIntent() 方法即可,该方法会收到每次 start 请求的 intent,你可以针对每个请求做处理。
IntentService实现的代码也很简单,在IntentService内部定义了一个内部类ServiceHandler,顾名思义是继承Handler的,
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);
}
}
在onStart()中每次都会把activity传过来的intent发送给handler处理。
private volatile ServiceHandler mServiceHandler;
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
最后的处理在onHandleIntent(Intent intent)中,这个方法在IntentService里是一个抽象方法,由子类实现。
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/
@WorkerThread
protected abstract void onHandleIntent(Intent intent);
这里有个workerThread,我理解的是所有的activity传过来的intent处理都是在一个工作线程处理的,就是子线程的意思,并不在主线程。
因为在IntentService中重写了onCreate(),在里面申请了一个工作线程给了handler
@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);
}