IntentService继承自Service,用于异步处理一些后台耗时操作。在谷歌的建议中,我们不应该在Service中进行大量耗时操作,因为Service位于主线程,容易引起ANR。所以谷歌官方推出IntentService用于处理耗时操作。
在IntentService中,有一个继承自Handler的ServiceHandler内部类,此工作线程用来处理耗时操作。在实例化一个IntentService时,会首先调用onCreate()方法,在这个方法里面,会进行一些数据的初始化。首先我们会实例化一个HanlderThread类。并调用start()方法启动它。接着会将这个HandlerThread的Looper引用给IntentService,接着会实例化一个ServiceHandler并将Looper作为参数传递进去。到这里,通过Looper完成了两个线程之间的绑定。绑定后,内部通过消息的方式发送个HanlderThread(),然后由Hanlder中的Looper调取消息分发处理。
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);
}
接下来会继续调用onStartCommond()里的onStart()方法,在这个方法中会初始化一个Message,并用于消息的发送。
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
最后会调用ServiceHanlder里面的handlerMessage()方法,在方法内部调用onHandlerIntent()方法,处理接受到的消息。当只有一个消息时,处理完毕调用stopSelf()方法,销毁当前IntentService,如果多次调用startService,会多次调用onStartCommond()方法(onCreate()只调用一次)。这时,会形成一个消息队列,当一个消息处理完毕后,处理下一个消息。所有消息 处理完毕时,在调用stopSelf()方法。