个人博客:http://zhangsunyucong.top
前言
在这一篇文章中,会看HandlerThread和IntentService的源码。为什么一起讲它们呢?在Android中有一条思路,就是从java的线程,到Android中的消息机制,到将java线程和消息机制结合就是HandlerThread,而IntentService就是在HandlerThread基础上再与service结合在一起。
关于Android中的异步的东西,还有AsyncTask,AsyncTask是对java中的线程池的再次封装。进一步,可以联想到Loader.
回到本篇文章主题。
HandlerThread是一个直接继承于Thread的,并在run方法中将线程的Looper进行常规的初始化。而我们要做的就是提供一个Handler,并将Handler与HanderThread的Looper进行关联,通过Handler发送消息和处理消息。
IntentService直接继承于Service,在它的内部封装了HandlerThread的使用过程:提供一个Handler(即:ServiceHandler),并将Handler与HanderThread的Looper进行关联,然后它进一步将启动Service的Intent以消息的形式,通过Handler传给onHandleIntent方法,然后IntentService优雅的结束自己。我们要做的就是在onHandleIntent中做线程要做的事情。
源码
HandlerThread.jva
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
...
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
...
}
HandlerThread的run方法做了主要的工作。创建Looper,在onLooperPrepare做开始循环前的初始化工作,开始Looper循环。
在具体使用HandlerThread时,就是创建Handler,将Handler与HandlerThread的Looper进行关联,然后通过Handler发送消息,处理消息。说明,消息是在HandlerThread线程中处理的。
IntentService.java
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
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);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
...
@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);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
* This may be null if the service is being restarted after
* its process has gone away; see
* {@link android.app.Service#onStartCommand}
* for details.
*/
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
}
IntentService是一个service子类,在onCreate中初始化了HandlerThread和ServiceHandler,并将ServiceHandler与HandlerThread的Looper进行关联。在onStart中,将启动服务的Intent封装进Message中,然后发给ServiceHandler。ServiceHandler再将Intent传递给onHandleIntent,最后优雅的结束自己。
在具体使用IntentService时,就是在onHandleIntent中正确的处理启动service的Intent即可。说明,onHandleIntent做的事情是在HandlerThread中进行的,因为HandlerThread的Looper与ServiceHandler已经关联,onHandleIntent是在ServiceHandler中被调用的(好啰嗦)。