刚刚总结完了Handler和HandlerThread,刚才又去看了看IntentService。
@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);
}
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);
}
}
这里只是将handleMessage()中要处理的逻辑放在了IntentService自己的onHandleIntent()中,而这个方法就是我们自定义IntentService所要重写的。
IntentService有个特点,它自己就可以控制生命周期,而不用像service那样需要主动去关闭。stopSelf()会马上关掉自己,而不管是否还有消息没处理完。这里调用的stopSelf(int)则会判断是否还有消息,如果没有任务要处理了才将自己关闭。
如果任务较多,产生任务的速度快过处理任务的速度,这些任务就会在队列中等待,此时onCreate()只会在初次生成时调用,后面只会多次调用onStartCommand(),并用onHandleMessage()处理任务。如果任务较少,处理速度更快,则连续多次的startService()可能每次都产生新的IntentService。