IntentService是Android中针对处理异步请求而封装的类,使用者只需要继承IntentService,并重写其中的onHandleIntent(Intent) 方法,实现自己的处理逻辑。其优势在于:1,在单独线程中处理,不会对主线程造成堵塞;2,任务完成后,自动停止线程,避免了内存消耗。 下面就大略分析一下其原理吧,public abstract class IntentService extends Service {}可以看到IntentService继承自Service, 那么就依据其生命周期来依次看一下其执行逻辑:
@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);
}
可以看到在OnCreate()方法中只要做了两件事情:一是创建了HandlerThread实例并启动,二是使用创建的HandlerThread实例获取Looper创建 ServiceHandler对象,那么就来看一下ServiceHandler吧
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 方法中调用了onHandleIntent ,这也是使用者唯一需要实现的方法,至此,思路已经十分清楚了,可以在 其onStart()方法中看到 @Override public void onStart(@Nullable Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); } 通过ServiceHandler发送消息,从而使得整个流程联通,至此,大致关于其逻辑就可以明确了。