android中Message机制的灵活应用

关键字: 消息机制 handler looper 线程间通信 message messagequeue

引用 来自easyandroid论坛,原文:http://www.easyandroid.com/bbs/viewthread.php?tid=33
1.活用Android线程间通信的Message机制

1.1.Message
代码在frameworks\base\core\java\android\Os\Message.java中。

Message.obtain函数:有多个obtain函数,主要功能一样,只是参数不一样。作用是从Message Pool中取出一个Message,如果Message Pool中已经没有Message可取则新建一个Message返回,同时用对应的参数给得到的Message对象赋值。

Message Pool:大小为10个;通过Message.mPool->(Message并且Message.next)-> (Message并且Message.next)-> (Message并且Message.next)...构造一个Message Pool。Message Pool的第一个元素直接new出来,然后把Message.mPool(static类的static变量)指向它。其他的元素都是使用完的 Message通过Message的recycle函数清理后放到Message Pool(通过Message Pool最后一个Message的next指向需要回收的Message的方式实现)。下图为Message Pool的结构:


1.2.MessageQueue
MessageQueue里面有一个收到的Message的对列:

MessageQueue.mMessages(static变量)->( Message并且Message.next)-> ( Message并且Message.next)->...,下图为接收消息的消息队列:

上层代码通过Handler的sendMessage等函数放入一个message到MessageQueue里面时最终会调用MessageQueue的 enqueueMessage函数。enqueueMessage根据上面的接收的Message的队列的构造把接收到的Message放入队列中。

MessageQueue的removeMessages函数根据上面的接收的Message的队列的构造把接收到的Message从队列中删除,并且调用对应Message对象的recycle函数把不用的Message放入Message Pool中。

1.3.Looper
Looper对象的创建是通过prepare函数,而且每一个Looper对象会和一个线程关联

Java代码
  1. publicstaticfinalvoidprepare(){
  2. if(sThreadLocal.get()!=null){
  3. thrownewRuntimeException("OnlyoneLoopermaybecreatedperthread");
  4. }
  5. sThreadLocal.set(newLooper());
  6. }
public static final void prepare() {    if (sThreadLocal.get() != null) {        throw new RuntimeException("Only one Looper may be created per thread");    }    sThreadLocal.set(new Looper());}


Looper对象创建时会创建一个MessageQueue,主线程默认会创建一个Looper从而有MessageQueue,其他线程默认是没有 MessageQueue的不能接收Message,如果需要接收Message则需要通过prepare函数创建一个MessageQueue。具体操作请见示例代码。

Java代码
  1. privateLooper(){
  2. mQueue=newMessageQueue();
  3. mRun=true;
  4. mThread=Thread.currentThread();
  5. }
private Looper() {    mQueue = new MessageQueue();    mRun = true;    mThread = Thread.currentThread();}


prepareMainLooper函数只给主线程调用(系统处理,程序员不用处理),它会调用prepare建立Looper对象和MessageQueue。

Java代码
  1. publicstaticfinalvoidprepareMainLooper(){
  2. prepare();
  3. setMainLooper(myLooper());
  4. if(Process.supportsProcesses()){
  5. myLooper().mQueue.mQuitAllowed=false;
  6. }
  7. }
public static final void prepareMainLooper() {    prepare();    setMainLooper(myLooper());    if (Process.supportsProcesses()) {        myLooper().mQueue.mQuitAllowed = false;    }}


Loop函数从MessageQueue中从前往后取出Message,然后通过Handler的dispatchMessage函数进行消息的处理(可见消息的处理是Handler负责的),消息处理完了以后通过Message对象的recycle函数放到Message Pool中,以便下次使用,通过Pool的处理提供了一定的内存管理从而加速消息对象的获取。至于需要定时处理的消息如何做到定时处理,请见 MessageQueue的next函数,它在取Message来进行处理时通过判断MessageQueue里面的Message是否符合时间要求来决定是否需要把Message取出来做处理,通过这种方式做到消息的定时处理。

Java代码
  1. publicstaticfinalvoidloop(){
  2. Looperme=myLooper();
  3. MessageQueuequeue=me.mQueue;
  4. while(true){
  5. Messagemsg=queue.next();//mightblock
  6. //if(!me.mRun){
  7. //break;
  8. //}
  9. if(msg!=null){
  10. if(msg.target==null){
  11. //Notargetisamagicidentifierforthequitmessage
  12. return;
  13. }
  14. if(me.mLogging!=null)
  15. me.mLogging.println(">>>>>Dispatchingto"+msg.target+""+msg.callback+":"+msg.what);
  16. msg.target.dispatchMessage(msg);
  17. if(me.mLogging!=null)
  18. me.mLogging.println("<<<<<Finishedto"+msg.target+""+msg.callback);
  19. msg.recycle();
  20. }
  21. }
  22. }
public static final void loop() {    Looper me = myLooper();    MessageQueue queue = me.mQueue;    while (true) {        Message msg = queue.next(); // might block        //if (!me.mRun) {        //    break;        //}        if (msg != null) {            if (msg.target == null) {                // No target is a magic identifier for the quit message                return;            }            if (me.mLogging!= null)                 me.mLogging.println(">>>>> Dispatching to " + msg.target + " "+ msg.callback + ": " + msg.what);            msg.target.dispatchMessage(msg);            if (me.mLogging!= null)                 me.mLogging.println("<<<<< Finished to" + msg.target + " "+ msg.callback);            msg.recycle();        }    }}


1.4.Handler

Handler的构造函数表示Handler会有成员变量指向Looper和MessageQueue,后面我们会看到没什么需要这些引用;至于callback是实现了Callback接口的对象,后面会看到这个对象的作用。

Java代码
  1. publicHandler(Looperlooper,Callbackcallback){
  2. mLooper=looper;
  3. mQueue=looper.mQueue;
  4. mCallback=callback;
  5. }
  6. publicinterfaceCallback{
  7. publicbooleanhandleMessage(Messagemsg);
  8. }
public Handler(Looper looper, Callback callback) {    mLooper = looper;    mQueue = looper.mQueue;    mCallback = callback;}public interface Callback {    public boolean handleMessage(Message msg);}


获取消息:直接通过Message的obtain方法获取一个Message对象。

Java代码
  1. publicfinalMessageobtainMessage(intwhat,intarg1,intarg2,Objectobj){
  2. returnMessage.obtain(this,what,arg1,arg2,obj);
  3. }
public final Message obtainMessage(int what, int arg1, int arg2, Object obj){    return Message.obtain(this, what, arg1, arg2, obj);}


发送消息:通过MessageQueue的enqueueMessage把Message对象放到MessageQueue的接收消息队列中

Java代码
  1. publicbooleansendMessageAtTime(Messagemsg,longuptimeMillis){
  2. booleansent=false;
  3. MessageQueuequeue=mQueue;
  4. if(queue!=null){
  5. msg.target=this;
  6. sent=queue.enqueueMessage(msg,uptimeMillis);
  7. }else{
  8. RuntimeExceptione=newRuntimeException(this+"sendMessageAtTime()calledwithnomQueue");
  9. Log.w("Looper",e.getMessage(),e);
  10. }
  11. returnsent;
  12. }
public boolean sendMessageAtTime(Message msg, long uptimeMillis){    boolean sent = false;    MessageQueue queue = mQueue;    if (queue != null) {        msg.target = this;    sent = queue.enqueueMessage(msg, uptimeMillis);    } else {        RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");        Log.w("Looper", e.getMessage(), e);    }    return sent;}



线程如何处理MessageQueue中接收的消息:在Looper的loop函数中循环取出MessageQueue的接收消息队列中的消息,然后调用 Hander的dispatchMessage函数对消息进行处理,至于如何处理(相应消息)则由用户指定(三个方法,优先级从高到低:Message里面的Callback,一个实现了Runnable接口的对象,其中run函数做处理工作;Handler里面的mCallback指向的一个实现了 Callback接口的对象,里面的handleMessage进行处理;处理消息Handler对象对应的类继承并实现了其中 handleMessage函数,通过这个实现的handleMessage函数处理消息)。

Java代码
  1. publicvoiddispatchMessage(Messagemsg){
  2. if(msg.callback!=null){
  3. handleCallback(msg);
  4. }else{
  5. if(mCallback!=null){
  6. if(mCallback.handleMessage(msg)){
  7. return;
  8. }
  9. }
  10. handleMessage(msg);
  11. }
  12. }
public void dispatchMessage(Message msg) {    if (msg.callback != null) {        handleCallback(msg);    } else {        if (mCallback != null) {            if (mCallback.handleMessage(msg)) {                return;            }        }        handleMessage(msg);    }}


Runnable说明:Runnable只是一个接口,实现了这个接口的类对应的对象也只是个普通的对象,并不是一个Java中的Thread。Thread类经常使用Runnable,很多人有误解,所以这里澄清一下。


从上可知以下关系图:

其中清理Message是Looper里面的loop函数指把处理过的Message放到Message的Pool里面去,如果里面已经超过最大值10个,则丢弃这个Message对象。

调用Handler是指Looper里面的loop函数从MessageQueue的接收消息队列里面取出消息,然后根据消息指向的Handler对象调用其对应的处理方法。
1.5.代码示例

下面我们会以android实例来展示对应的功能,程序界面于下:

程序代码如下,后面部分有代码说明:

Java代码
  1. packagecom.android.messageexample;
  2. importandroid.app.Activity;
  3. importandroid.content.Context;
  4. importandroid.graphics.Color;
  5. importandroid.os.Bundle;
  6. importandroid.os.Handler;
  7. importandroid.os.Looper;
  8. importandroid.os.Message;
  9. importandroid.util.Log;
  10. importandroid.view.View;
  11. importandroid.view.View.OnClickListener;
  12. importandroid.widget.Button;
  13. importandroid.widget.LinearLayout;
  14. importandroid.widget.TextView;
  15. publicclassMessageExampleextendsActivityimplementsOnClickListener{
  16. privatefinalintWC=LinearLayout.LayoutParams.WRAP_CONTENT;
  17. privatefinalintFP=LinearLayout.LayoutParams.FILL_PARENT;
  18. publicTextViewtv;
  19. privateEventHandlermHandler;
  20. privateHandlermOtherThreadHandler=null;
  21. privateButtonbtn,btn2,btn3,btn4,btn5,btn6;
  22. privateNoLooperThreadnoLooerThread=null;
  23. privateOwnLooperThreadownLooperThread=null;
  24. privateReceiveMessageThreadreceiveMessageThread=null;
  25. privateContextcontext=null;
  26. privatefinalStringsTag="MessageExample";
  27. privatebooleanpostRunnable=false;
  28. /**Calledwhentheactivityisfirstcreated.*/
  29. @Override
  30. publicvoidonCreate(BundlesavedInstanceState){
  31. super.onCreate(savedInstanceState);
  32. context=this.getApplicationContext();
  33. LinearLayoutlayout=newLinearLayout(this);
  34. layout.setOrientation(LinearLayout.VERTICAL);
  35. btn=newButton(this);
  36. btn.setId(101);
  37. btn.setText("messagefrommainthreadself");
  38. btn.setOnClickListener(this);
  39. LinearLayout.LayoutParamsparam=
  40. newLinearLayout.LayoutParams(250,50);
  41. param.topMargin=10;
  42. layout.addView(btn,param);
  43. btn2=newButton(this);
  44. btn2.setId(102);
  45. btn2.setText("messagefromotherthreadtomainthread");
  46. btn2.setOnClickListener(this);
  47. layout.addView(btn2,param);
  48. btn3=newButton(this);
  49. btn3.setId(103);
  50. btn3.setText("messagetootherthreadfromitself");
  51. btn3.setOnClickListener(this);
  52. layout.addView(btn3,param);
  53. btn4=newButton(this);
  54. btn4.setId(104);
  55. btn4.setText("messagewithRunnableascallbackfromotherthreadtomainthread");
  56. btn4.setOnClickListener(this);
  57. layout.addView(btn4,param);
  58. btn5=newButton(this);
  59. btn5.setId(105);
  60. btn5.setText("mainthread'smessagetootherthread");
  61. btn5.setOnClickListener(this);
  62. layout.addView(btn5,param);
  63. btn6=newButton(this);
  64. btn6.setId(106);
  65. btn6.setText("exit");
  66. btn6.setOnClickListener(this);
  67. layout.addView(btn6,param);
  68. tv=newTextView(this);
  69. tv.setTextColor(Color.WHITE);
  70. tv.setText("");
  71. LinearLayout.LayoutParamsparam2=
  72. newLinearLayout.LayoutParams(FP,WC);
  73. param2.topMargin=10;
  74. layout.addView(tv,param2);
  75. setContentView(layout);
  76. //主线程要发送消息给otherthread,这里创建那个otherthread
  77. receiveMessageThread=newReceiveMessageThread();
  78. receiveMessageThread.start();
  79. }
  80. //implementtheOnClickListenerinterface
  81. @Override
  82. publicvoidonClick(Viewv){
  83. switch(v.getId()){
  84. case101:
  85. //主线程发送消息给自己
  86. Looperlooper;
  87. looper=Looper.myLooper();//gettheMainlooperrelatedwiththemainthread
  88. //如果不给任何参数的话会用当前线程对应的Looper(这里就是MainLooper)为Handler里面的成员mLooper赋值
  89. mHandler=newEventHandler(looper);
  90. //mHandler=newEventHandler();
  91. //清除整个MessageQueue里的消息
  92. mHandler.removeMessages(0);
  93. Stringobj="Thismainthread'smessageandreceivedbyitself!";
  94. //得到Message对象
  95. Messagem=mHandler.obtainMessage(1,1,1,obj);
  96. //将Message对象送入到mainthread的MessageQueue里面
  97. mHandler.sendMessage(m);
  98. break;
  99. case102:
  100. //other线程发送消息给主线程
  101. postRunnable=false;
  102. noLooerThread=newNoLooperThread();
  103. noLooerThread.start();
  104. break;
  105. case103:
  106. //otherthread获取它自己发送的消息
  107. tv.setText("pleaselookattheerrorlevellogforotherthreadreceivedmessage");
  108. ownLooperThread=newOwnLooperThread();
  109. ownLooperThread.start();
  110. break;
  111. case104:
  112. //otherthread通过PostRunnable方式发送消息给主线程
  113. postRunnable=true;
  114. noLooerThread=newNoLooperThread();
  115. noLooerThread.start();
  116. break;
  117. case105:
  118. //主线程发送消息给otherthread
  119. if(null!=mOtherThreadHandler){
  120. tv.setText("pleaselookattheerrorlevellogforotherthreadreceivedmessagefrommainthread");
  121. StringmsgObj="messagefrommainThread";
  122. MessagemainThreadMsg=mOtherThreadHandler.obtainMessage(1,1,1,msgObj);
  123. mOtherThreadHandler.sendMessage(mainThreadMsg);
  124. }
  125. break;
  126. case106:
  127. finish();
  128. break;
  129. }
  130. }
  131. classEventHandlerextendsHandler
  132. {
  133. publicEventHandler(Looperlooper){
  134. super(looper);
  135. }
  136. publicEventHandler(){
  137. super();
  138. }
  139. publicvoidhandleMessage(Messagemsg){
  140. //可以根据msg.what执行不同的处理,这里没有这么做
  141. switch(msg.what){
  142. case1:
  143. tv.setText((String)msg.obj);
  144. break;
  145. case2:
  146. tv.setText((String)msg.obj);
  147. noLooerThread.stop();
  148. break;
  149. case3:
  150. //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
  151. Log.e(sTag,(String)msg.obj);
  152. ownLooperThread.stop();
  153. break;
  154. default:
  155. //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
  156. Log.e(sTag,(String)msg.obj);
  157. break;
  158. }
  159. }
  160. }
  161. //NoLooperThread
  162. classNoLooperThreadextendsThread{
  163. privateEventHandlermNoLooperThreadHandler;
  164. publicvoidrun(){
  165. LoopermyLooper,mainLooper;
  166. myLooper=Looper.myLooper();
  167. mainLooper=Looper.getMainLooper();//这是一个static函数
  168. Stringobj;
  169. if(myLooper==null){
  170. mNoLooperThreadHandler=newEventHandler(mainLooper);
  171. obj="NoLooperThreadhasnolooperandhandleMessagefunctionexecutedinmainthread!";
  172. }
  173. else{
  174. mNoLooperThreadHandler=newEventHandler(myLooper);
  175. obj="ThisisfromNoLooperThreadselfandhandleMessagefunctionexecutedinNoLooperThread!";
  176. }
  177. mNoLooperThreadHandler.removeMessages(0);
  178. if(false==postRunnable){
  179. //sendmessagetomainthread
  180. Messagem=mNoLooperThreadHandler.obtainMessage(2,1,1,obj);
  181. mNoLooperThreadHandler.sendMessage(m);
  182. Log.e(sTag,"NoLooperThreadid:"+this.getId());
  183. }else{
  184. //下面new出来的实现了Runnable接口的对象中run函数是在MainThread中执行,不是在NoLooperThread中执行
  185. //注意Runnable是一个接口,它里面的run函数被执行时不会再新建一个线程
  186. //您可以在run上加断点然后在eclipse调试中看它在哪个线程中执行
  187. mNoLooperThreadHandler.post(newRunnable(){
  188. @Override
  189. publicvoidrun(){
  190. tv.setText("updateUIthroughhandlerpostrunnalbemechanism!");
  191. noLooerThread.stop();
  192. }
  193. });
  194. }
  195. }
  196. }
  197. //OwnLooperThreadhashisownmessagequeuebyexecuteLooper.prepare();
  198. classOwnLooperThreadextendsThread{
  199. privateEventHandlermOwnLooperThreadHandler;
  200. publicvoidrun(){
  201. Looper.prepare();
  202. LoopermyLooper,mainLooper;
  203. myLooper=Looper.myLooper();
  204. mainLooper=Looper.getMainLooper();//这是一个static函数
  205. Stringobj;
  206. if(myLooper==null){
  207. mOwnLooperThreadHandler=newEventHandler(mainLooper);
  208. obj="OwnLooperThreadhasnolooperandhandleMessagefunctionexecutedinmainthread!";
  209. }
  210. else{
  211. mOwnLooperThreadHandler=newEventHandler(myLooper);
  212. obj="ThisisfromOwnLooperThreadselfandhandleMessagefunctionexecutedinNoLooperThread!";
  213. }
  214. mOwnLooperThreadHandler.removeMessages(0);
  215. //给自己发送消息
  216. Messagem=mOwnLooperThreadHandler.obtainMessage(3,1,1,obj);
  217. mOwnLooperThreadHandler.sendMessage(m);
  218. Looper.loop();
  219. }
  220. }
  221. //ReceiveMessageThreadhashisownmessagequeuebyexecuteLooper.prepare();
  222. classReceiveMessageThreadextendsThread{
  223. publicvoidrun(){
  224. Looper.prepare();
  225. mOtherThreadHandler=newHandler(){
  226. publicvoidhandleMessage(Messagemsg){
  227. Log.e(sTag,(String)msg.obj);
  228. }
  229. };
  230. Looper.loop();
  231. }
  232. }
  233. }
package com.android.messageexample;import android.app.Activity;import android.content.Context;import android.graphics.Color;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.LinearLayout;import android.widget.TextView;public class MessageExample extends Activity implements OnClickListener { private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;  private final int FP = LinearLayout.LayoutParams.FILL_PARENT;  public TextView tv;  private EventHandler mHandler;  private Handler mOtherThreadHandler=null;  private Button btn, btn2, btn3, btn4, btn5, btn6;  private NoLooperThread noLooerThread = null;  private OwnLooperThread ownLooperThread = null;  private ReceiveMessageThread receiveMessageThread =null;  private Context context = null;  private final String sTag = "MessageExample";  private boolean postRunnable = false;  /** Called when the activity is first created. */ @Override  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  context = this.getApplicationContext();  LinearLayout layout = new LinearLayout(this);  layout.setOrientation(LinearLayout.VERTICAL);  btn = new Button(this);  btn.setId(101);  btn.setText("message from main thread self");  btn.setOnClickListener(this);  LinearLayout.LayoutParams param =    new LinearLayout.LayoutParams(250,50);  param.topMargin = 10;  layout.addView(btn, param);  btn2 = new Button(this);  btn2.setId(102);  btn2.setText("message from other thread to main thread");  btn2.setOnClickListener(this);  layout.addView(btn2, param);  btn3 = new Button(this);  btn3.setId(103);  btn3.setText("message to other thread from itself");  btn3.setOnClickListener(this);  layout.addView(btn3, param);  btn4 = new Button(this);  btn4.setId(104);  btn4.setText("message with Runnable as callback from other thread to main thread");  btn4.setOnClickListener(this);  layout.addView(btn4, param);  btn5 = new Button(this);  btn5.setId(105);  btn5.setText("main thread's message to other thread");  btn5.setOnClickListener(this);  layout.addView(btn5, param);  btn6 = new Button(this);  btn6.setId(106);  btn6.setText("exit");  btn6.setOnClickListener(this);  layout.addView(btn6, param);  tv = new TextView(this);  tv.setTextColor(Color.WHITE);  tv.setText("");  LinearLayout.LayoutParams param2 =   new LinearLayout.LayoutParams(FP, WC);  param2.topMargin = 10;  layout.addView(tv, param2);  setContentView(layout);     //主线程要发送消息给other thread, 这里创建那个other threadreceiveMessageThread = new ReceiveMessageThread();receiveMessageThread.start();  }  //implement the OnClickListener interface @Override public void onClick(View v) {switch(v.getId()){case 101: //主线程发送消息给自己 Looper looper; looper = Looper.myLooper();//get the Main looper related with the main thread //如果不给任何参数的话会用当前线程对应的Looper(这里就是Main Looper)为Handler里面的成员mLooper赋值 mHandler = new EventHandler(looper);  //mHandler = new EventHandler(); // 清除整个MessageQueue里的消息 mHandler.removeMessages(0); String obj = "This main thread's message and received by itself!"; //得到Message对象 Message m = mHandler.obtainMessage(1, 1, 1, obj); // 将Message对象送入到main thread的MessageQueue里面 mHandler.sendMessage(m); break;case 102:   //other线程发送消息给主线程 postRunnable = false; noLooerThread = new NoLooperThread(); noLooerThread.start(); break;case 103: //other thread获取它自己发送的消息 tv.setText("please look at the error level log for other thread received message"); ownLooperThread = new OwnLooperThread(); ownLooperThread.start(); break; case 104:  //other thread通过Post Runnable方式发送消息给主线程 postRunnable = true; noLooerThread = new NoLooperThread(); noLooerThread.start(); break;case 105:  //主线程发送消息给other thread if(null!=mOtherThreadHandler){  tv.setText("please look at the error level log for other thread received message from main thread");  String msgObj = "message from mainThread";  Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);  mOthe  
分享到: 深入Android 【二】 —— 架构和特征 | IntentFilter
  • 2010-04-27 09:22
  • 浏览 446
  • 评论(0)
  • 分类:移动开发
  • 相关推荐
评论
发表评论

您还没有登录,请您登录后再发表评论

更多相关文章

  1. Android的IPC机制Binder的详解汇总
  2. android recovery 和reboot
  3. android下对xml的解析
  4. Android(安卓)EditText 共用TextWatcher,在TextWatcher中确定对应
  5. Intent调用
  6. Android的“垃圾回收机制”---智能指针(android refbase类(sp wp))
  7. Android(安卓)时间对象操作工具类
  8. android中进度条控件
  9. Android休眠唤醒机制简介(二)

随机推荐

  1. Android7.0中文文档(API)-- Toast
  2. My Android(安卓)Camera Notes
  3. Android:GridView+AbsoluteLayout作一个
  4. android ImageView scaleType属性
  5. Android常用控件
  6. RadioButton修改标志图片
  7. 样式和主题-style&them
  8. Android下单元测试
  9. 最近总结的android疑惑
  10. Android下修改ImageButton样式