HandlerThread
HandlerThread 继承 Thread,是一种可以使用 Handler 的 Thread ,它的具体实现,就是在 run 方法中通过 Looper.prepare() 来创建消息队列,并通过 Looper.loop() 来开启消息循环。run 方法具体代码实现如下:
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}从HandlerThread 的 run 方法实现来看,与普通的 Thread 会有一些不同。普通的 Thread 的 run 方法中主要是执行一些耗时的任务,而 HandlerThread 的 run 方法中,是创建一个消息队列,外界需要通过 Handler 的发送消息的方法来通知 HandlerThread 方法执行任务。由于 HandlerThread 的 run 方法是一个无限循环,所以当不再使用 HandlerThread 的情况下,记得调用它的 quit 或者 quitSafely 方法来终止线程的执行。
IntentService
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);
} 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);
}
} public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
本文介绍了Android中HandlerThread和IntentService的工作原理及其内部实现机制。HandlerThread通过Looper创建消息队列并开启消息循环,而IntentService利用HandlerThread实现后台任务的有序执行。
568

被折叠的 条评论
为什么被折叠?



