IntentService源码分析
一、什么是IntentService
IntentService继承自Service并且本身就是一个抽象类
它可以用于在后台执行耗时的异步任务,当任务完成后会自动停止。
二、IntentService源码分析
先来看下IntentService的类结构
内部类ServiceHandler是一个Handler的子类,简单的实现了handleMessage
并在接收到消息时调用onHandleIntent,然后调用stopSelf退出service。
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);
}
}
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName; //
private boolean mRedelivery;
构造函数参数name是用来给工作线程命名用的。
public IntentService(String name) {
super();
mName = name;
}
IntentService继承自service那么根据service的生命周期,首先会调用onCreate函数
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 + "]");//构造HandlerThread 实例
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);//构造ServiceHandler实例
}
在onCreate函数内部先构造了一个HandlerThread,然后调用了其start函数。之后还获取了HandlerThread的looper,并用该looper构造了ServiceHandler实例。
这里的HandlerThread实际是一个Thread类,其作用就是作为工作线程异步处理IntentService的任务。主要关注其run函数,在run函数内部其调用了Looper.prepare()和Looper.loop(),这样就开启了looper循环。
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();//构造looper
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();//开启looper循环
mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
}
接着看IntentService,oncreate之后便是onStartCommand,它内部只是简单调用了onStart。我们来看onStart,它内部就是构造一个携带intent的Message并将其通过mServiceHandler发送出去。
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
这样消息就会在ServiceHandler的handlemessage中被处理,我们之前已经看过了handlemessage会调用onHandleIntent然后调用stopself停止。
onHandleIntent是一个抽象方法,我们继承IntentService实现该方法并在内部完成我们想要的操作。onHandleIntent运行在工作线程即HandlerThread中。
protected abstract void onHandleIntent(@Nullable Intent intent);
以上就是IntentService的源码解析,通过分析我们知道IntentService的异步处理请求是通过handler来完成的,它在内部构造了一个Theard作为工作线程,在该Theard的run方法中开启了looper循环,然后每当启动IntentService后会通过handler来异步处理。所以IntentService本质是service+handler。