IntentService 源码分析
结构:继承与Service,运行于后台的服务,包含了HandlerThread,而HandlerThread 是包含了线程和Handler的
问题:IntentService是如何执行耗时操作的
1.首先会再onCreate 函数执行创建HandlerThread的操作,并拿到HandlerThread的looper
@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);
}
问题:是如何拿到looper的,拿到的looper是子线程的,还是主线程的looper,并创建了对应的handler
HandlerThread 在start的时候,就会执行线程的run方法,在run方法创建了looper,创建的为子线程的looper
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
2.在onStart() 通过hander 发送消息
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
3.IntentService 收到消息后,便执行onHandleIntent方法,onHandleIntent便为子线程中执行的函数
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);
}
}
总结:其实IntentService 即保留了Service的特性,有提供了线程,供执行了耗时操作。而线程通过HanlderThread 的来承载,达到了处理异步任务的能力.
如何看源码?
其实源码没那么难,先提出问题,带着问题去看源码,还是比较顺畅的,可以先从一些关联不大的类开始,到后面分析更大的框架等,循序渐进。
看源码的作用?
源码中的点会有很多JAVA 技术的运行,可以对以前的知识进行串联,巩固,形成知识体系,就不会容易忘记了