1、Service不能编写耗时的逻辑和操作,否则会引起ANR(ANR全称:Application Not Responding,也就是应用程序无响应。),因此引入了IntentService
2、IntentService:继承并处理异步请求的一个类,内部有一个工作线程HandlerThread来处理耗时操作(通过消息的方式发送给HandlerThread,然后由handler中looper来处理消息),可以启动IntentService多次,而每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推,当任务执行完后,会自动停止
3、源码
a、创建工作线程并启动,初始化Handler和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);
}
b、发送消息给Handler
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
c、ServiceHandler处理消息执行耗时操作
protected abstract void onHandleIntent(@Nullable Intent intent);