IntentService继承了Service,在IntentService内有一个工作线程来处理耗时操作。IntentService封装了handlerThread和Handler,在IntentService的onCreate()中创建并启动了handlerThread对象,利用handlerThread的looper对象又创建了Handler对象。每次启动Intentservice,onStartCommand(Intent intent)就会被调用一次,在onStartCommand中又调用了onStart(Intent intent),在onStart(Intent intent)方法里将intent赋值给了message,并通过Handler发送message到子线程的Looper,这个消息就会在handlerThread中处理。Handler收到消息后,会把intent对象传递给onHandleIntent(Intent intent)方法中处理,在onHandleIntent做耗时操作,onHandleIntent执行完后,IntentService会通过stopSelf(int startId)停止服务。多次启动同一个IntentService执行多个任务,只会创建一个service实例,但会开启多个线程,多个线程会按开启顺序串行执行(一个线程执行完成,另一个线程才会执行),所有任务执行完成后,IntentService会自动停止并销毁。
参考链接:
http://www.tuicool.com/articles/zeMFFvB