子线程新建Handler为什么会报错?——浅谈Handler、Looper、Message关系
转载注明出处:
http://blog.csdn.net/u010181592/article/category/5893483
文章出自 我不只是看客的博客
很多人都知道不能直接在子线程new 一个Handler,android会报错,至于为什么会报错,并没有做深入的研究,今天就来研究一下,顺手学习了下android异步消息处理机制的问题,一起放出来。
列出参考资料:
Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系 出自 鸿洋大神的博客;
常见面试题
- 在子线程中new一个Handler为什么报错?
下边来重现一下错误的做法:
首先,直接在子线程新建一个handler
new Thread(new Runnable() { @Override public void run() { //这里写入子线程需要做的工作 Log.e("wanghe","asdasdasd"); Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show(); } }; handler.sendEmptyMessage(1); } }).start();
运行之后,不出意外的报错
错误信息:
java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()
不能再子线程中新建handler,没有呼叫Looper.prepare();,为什么呢,看一下handler的源码
public Handler() { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = null; }
handler构造函数中 需要持有一个looper的对象,如果没有,提示这个错误;
looper的主要作用是与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。然后looper的loop()方法就是不断从MessageQueue中取出消息,交给handler去发送消息。 而子线程是没有默认looper的,所以就会报错了。 解决办法也很简单,我们只需要调用prepare()方法,新建looper对象就好。看一下prepare都干了什么:
Looper.prepare()
public static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(true)); }
可以看到 方法中新建一个looper对象防放进了一个ThreadLocal的对象中,并且提前判断了ThreadLoacl是否为空,这就说明了prepare()不能被调用2次,也就保证了一个线程只能有一个looper;
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mRun = true; mThread = Thread.currentThread(); }
构造中 新建了一个MessageQueue,现在,消息队列找到了,怎么从中这个队列中拿出消息给handler呢?调用Looper.loop;
Looper.loop()
public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycle(); } } public static Looper myLooper() { return sThreadLocal.get();}
在myLooper中直接拿到了ThreadLoacl中存储的Looper实例,如果null就抛出,说明loop一定要在prepare之后调用;然后拿到了looper中的消息队列,进入无限循环,取消息->把消息嫁给msg的target的dispatchMessage方法处理,这个Msg的target是什么呢,就是我们很熟悉的Handler(饶了一圈终于找回来了。。。)
而在handler的源码中我们看到 handler通过持有的looper获取了looper的MessageQueue,这样就把Handler,looper ,message关联到了一起,
都走到这里了,就一口气看完handler处理message的逻辑吧
sendMessage()
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); } public final boolean sendEmptyMessageDelayed(int what, long delayMillis) { Message msg = Message.obtain(); msg.what = what; return sendMessageDelayed(msg, delayMillis); } public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }
最后调用到了endMessageAtTime,在此方法内部有直接获取MessageQueue然后调用了enqueueMessage方法,我们再来看看此方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
还记得上文looper.loop中会去除每个msg然后交给target.dispatchMessage(msg)去处理消息么?
enqueueMessage中首先为meg.target赋值为this,也就是把当前的handler作为msg的target属性。最终会调用queue的enqueueMessage的方法,也就是说handler发出的消息,最终会保存到消息队列中去。
现在已经很清楚了Looper会调用prepare()和loop()方法,在当前执行的线程中保存一个Looper实例,这个实例会保存一个MessageQueue对象,然后当前线程进入一个无限循环中去,不断从MessageQueue中读取Handler发来的消息。然后再回调创建这个消息的handler中的dispathMessage方法,下面我们赶快去看一看这个方法:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
这里最终调用了我们创建handler中复写的handlerMessage方法。
到此,整个流程基本理顺了一遍。
总结一下三者:
- 首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。
- Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。
- Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。
- Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。
- 在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。
总结完了,有人可能还会问,为什么UI线程中,并没有显示调用looper的prepare和loop方法,为什么就可以成功创建handler,因为在acitvity的启动代码中,就已经调用了looper的prepare和loop。
一句话总结:
Looper负责的就是创建一个MessageQueue,然后进入一个无限循环体不断从该MessageQueue中读取消息,而消息的创建者就是一个或多个Handler 。
后记
至此我们从一个常见的问题,引出来 很多人都头疼的handler异步消息机制问题,查找了一些源码,希望对各位有帮助
更多相关文章
- Android自定义属性时TypedArray的使用方法
- QtAndroid详解(3):startActivity实战Android拍照功能
- AsyncTask 学习翻译并总结
- Android所需的Java基础知识体系图
- Android(安卓)SQLite详解
- android中Webview与javascript的交互(互相调用)
- android 的handler 机制
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用