您的位置:首页 > 移动开发 > Android开发

理解Android消息处理系统 -- Handler & Message & Looper & ThreadLocal

2012-09-17 09:44 477 查看
 

2014-2-8号补充:

今天又看Handler的原理,又有更深的理解,发现每次看都会有更进一步的理解。

有几个类有必要看看:

Handler, Looper, HandlerThread, ThreadLocal<T>, Message, MessageQueue, Parcelable,差不多了,涉及到的东西太多了。。。
http://mobile.51cto.com/abased-375243.htm http://www.2cto.com/kf/201312/262268.html http://blog.csdn.net/gemmem/article/details/7298760 http://blog.csdn.net/stonecao/article/details/6417364 http://zhidao.baidu.com/link?url=ywXTIYeaWRbDzSSu_iuJ3xs0f6v6GqlVhNhsfsuyXsjJ8xfVdJoLTwkY8-HLvygs3njNKWeQeQZSpcgqcPvyKq
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Handler这个类我想几乎所有写过android代码的人应该都用过,你分析过它么?知道它的工作原理么?

看下Looper这个类的解释:

android.os.Looper

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call
prepare
in the thread that is to run the
loop, and then
loop
to have it process messages until the loop is stopped.

Most interaction with a message loop is through the
Handler
class.

This is a typical example of the implementation of a Looper thread, using the separation of
prepare
and
loop

to create an initial Handler to communicate with the Looper.

class LooperThread extends Thread {
public Handler mHandler;

public void run() {
Looper.prepare();

mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};

Looper.loop();
}
}


 

Looper  ThreadLocal<T>  MessageQueue  Message Handler 这5个类应该是必须掌握的,看了看Looper的源码,表示压力好大,涉及到好多东西:

首先看下prepare()这个方法,解释如下:

Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call
loop()

after calling this method, and end it by calling
quit()
.

每次生成looper之前,必须调用,并通过threadloacal设置到当前线程中去。

public static final void prepare()

 

这个是UI线程的looper,通过static 变量mMainLooper来存储

public static final void prepareMainLooper() 

 

Run the message queue in this thread. Be sure to call
quit()
to end the loop.

运行消息队列:

public static final void loop()

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: