IntentService继承自Service,包装了一个带Looper的线程
由于Service运行在UI线程中,所有耗时的操作都需要新启一个Thread进行处理
一般的Thread是没有消息队列的,IntentSerivce中通过使用HandlerThread(定义了消息队列)
1.首先在onCreate中创建了一个HandlerThread线程并调用了start方法启动
@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); }
2.我们看下HandlerThread,在start之后调用了run方法
而run方法中初始化了消息队列Looper.prepare以及Looper.loop(),使得HandlerThread线程具有了Looper消息循环的功能,可以使用Handler对此线程进行消息队列的添加与处理
public class HandlerThread extends Thread { int mPriority; int mTid = -1; Looper mLooper; 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(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; } /** * This method returns the Looper associated with this thread. If this thread not been started * or for any reason is 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; } /** * Quits the handler thread's looper. * <p> * Causes the handler thread's looper to terminate without processing any * more messages in the message queue. * </p><p> * Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. * </p><p class="note"> * Using this method may be unsafe because some messages may not be delivered * before the looper terminates. Consider using {@link #quitSafely} instead to ensure * that all pending work is completed in an orderly manner. * </p> * * @return True if the looper looper has been asked to quit or false if the * thread had not yet started running. * * @see #quitSafely */ public boolean quit() { Looper looper = getLooper(); if (looper != null) { looper.quit(); return true; } return false; } /** * Quits the handler thread's looper safely. * <p> * Causes the handler thread's looper to terminate as soon as all remaining messages * in the message queue that are already due to be delivered have been handled. * Pending delayed messages with due times in the future will not be delivered. * </p><p> * Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. * </p><p> * If the thread has not been started or has finished (that is if * {@link #getLooper} returns null), then false is returned. * Otherwise the looper is asked to quit and true is returned. * </p> * * @return True if the looper looper has been asked to quit or false if the * thread had not yet started running. */ public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; } /** * Returns the identifier of this thread. See Process.myTid(). */ public int getThreadId() { return mTid; } }
3.通过thread.getLooper获取线程的Looper对象(由于使用了ThreadLocal,所以同一线程中只会存在唯一的Looper对象)
将Looper作为Handler构造参数,创建Handler
mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper);
4.Handler构造方法,mQueue为Looper中的消息队列
public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
5.handler.sendMessage会将Message消息添加到mQueue中,而Looper会在循环的时候,不停的获取MessageQueue中消息,然后再分发给Handler.handleMessage进行处理
前言
上周对Android中的事件派发机制进行了分析,这次博主要对消息队列和Looper的源码进行简单的分析。大家耐心看下去,其实消息队列的逻辑比事件派发机制简单多了,所以大家肯定会很容易看懂的。
概念
1. 什么是消息队列
消息队列在android中对应MessageQueue这个类,顾名思义,消息队列中存放了大量的消息(Message)
2.什么是消息
消息(Message)代表一个行为(what)或者一串动作(Runnable),有两处会用到Message:Handler和Messenger
3.什么是Handler和Messenger
Handler大家都知道,主要用来在线程中发消息通知ui线程更新ui。Messenger可以翻译为信使,可以实现进程间通信(IPC),Messenger采用一个单线程来处理所有的消息,而且进程间的通信都是通过发消息来完成的,感觉不能像AIDL那样直接调用对方的接口方法(具体有待考证),这是其和AIDL的主要区别,也就是说Messenger无法处理多线程,所有的调用都是在一个线程中串行执行的。Messenger的典型代码是这样的:new Messenger(service).send(msg),它的本质还是调用了Handler的sendMessage方法
4.什么是Looper
Looper是循环的意思,它负责从消息队列中循环的取出消息然后把消息交给目标处理
5.线程有没有Looper有什么区别?
线程如果没有Looper,就没有消息队列,就无法处理消息,线程内部就无法使用Handler。这就是为什么在子线程内部创建Handler会报错:"Can't create handler inside thread that has not called Looper.prepare()",具体原因下面再分析。
6.如何让线程有Looper从而正常使用Handler?
在线程的run方法中加入如下两句:
Looper.prepare();
Looper.loop();
这一切不用我们来做,有现成的,HandlerThread就是带有Looper的线程。
想用线程的Looper来创建Handler,很简单,Handler handler = new Handler(thread.getLooper()),有了上面这几步,你就可以在子线程中创建Handler了,好吧,其实android早就为我们想到这一点了,也不用自己写,IntentService把我们该做的都做了,我们只要用就好了,具体怎么用后面再说。
消息队列和Looper的工作机制
一个Handler会有一个Looper,一个Looper会有一个消息队列,Looper的作用就是循环的遍历消息队列,如果有新消息,就把新消息交给它的目标处理。每当我们用Handler来发送消息,消息就会被放入消息队列中,然后Looper就会取出消息发送给它的目标target。一般情况,一个消息的target是发送这个消息的Handler,这么一来,Looper就会把消息交给Handler处理,这个时候Handler的dispatchMessage方法就会被调用,一般情况最终会调用Handler的handleMessage来处理消息,用handleMessage来处理消息是我们常用的方式。
源码分析
1. Handler发送消息的过程
2.Looper的工作过程
3.Handler如何处理消息
我们再看看msg.callback和mCallback是啥东西
/*package*/ Runnable callback;
现在已经很明确了,msg.callback是个Runnable,什么时候会设置这个callback:handler.post(runnable),相信大家都常用这个方法吧
而mCallback是个接口,可以这样来设置 Handler handler = new Handler(callback),这个callback的意义是什么呢,代码里面的注释已经说了,可以让你不用创建Handler的子类但是还能照样处理消息,恐怕大家常用的方式都是新new一个Handler然后override其handleMessage方法来处理消息吧,从现在开始,我们知道,不创建Handler的子类也可以处理消息。多说一句,为什么创建Handler的子类不好?这是因为,类也是占空间的,一个应用class太多,其占用空间会变大,也就是应用会更耗内存。
HandlerThread简介
HandlerThread继承自Thread,其在run方法内部为自己创建了一个Looper,使用上HandlerThread和普通的Thread不一样,无法执行常见的后台操作,只能用来处理新消息,这是因为Looper.loop()是死循环,你的code根本执行不了,不过貌似你可以把你的code放在super.run()之前执行,但是这好像不是主流玩法,所以不建议这么做。
IntentService简介
IntentService继承自Service,它是一个抽象类,其被创建的时候就new了一个HandlerThread和ServiceHandler,有了它,就可以利用IntentService做一些优先级较高的task,IntentService不会被系统轻易杀掉。使用IntentService也是很简单,首先startService(intent),然后IntentService会把你的intent封装成Message然后通过ServiceHandler进行发送,接着ServiceHandler会调用onHandleIntent(Intent intent)来处理这个Message,onHandleIntent(Intent intent)中的intent就是你startService(intent)中的intent,ok,现在你需要做的是从IntentService派生一个子类并重写onHandleIntent方法,然后你只要针对不同的intent做不同的事情即可,事情完成后IntentService会自动停止。所以,IntentService是除了Thread和AsyncTask外又一执行耗时操作的方式,而且其不容易被系统干掉,建议关键操作采用IntentService。在子线程创建Handler为什么会报错?
如何避免这种错误:在ui线程使用Handler或者给子线程加上Looper。