现在的位置: 首页 > 综合 > 正文

ndroid中Message机制的灵活应用(二)

2013年01月16日 ⁄ 综合 ⁄ 共 9099字 ⁄ 字号 评论关闭
1.5.
代码示例



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


application_ui.GIF

 

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

 

说明(代码详细解释请见后文):

  1. package com.android.messageexample;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.graphics.Color;
  5. import android.os.Bundle;
  6. import android.os.Handler;
  7. import android.os.Looper;
  8. import android.os.Message;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.view.View.OnClickListener;
  12. import android.widget.Button;
  13. import android.widget.LinearLayout;
  14. import android.widget.TextView;
  15. public class MessageExample extends Activity implements OnClickListener {
  16. private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
  17. private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
  18. public TextView tv;
  19. private EventHandler mHandler;
  20. private Handler mOtherThreadHandler=null;
  21. private Button btn, btn2, btn3, btn4, btn5, btn6;
  22. private NoLooperThread noLooerThread = null;
  23. private OwnLooperThread ownLooperThread = null;
  24. private ReceiveMessageThread receiveMessageThread =null;
  25. private Context context = null;
  26. private final String sTag = "MessageExample";
  27. private boolean postRunnable = false;
  28. /** Called when the activity is first created. */
  29. @Override
  30. public void onCreate(Bundle savedInstanceState) {
  31.        super.onCreate(savedInstanceState);
  32.        context = this.getApplicationContext();
  33.        LinearLayout layout = new LinearLayout(this);
  34.        layout.setOrientation(LinearLayout.VERTICAL);
  35.        btn = new Button(this);
  36.        btn.setId(101);
  37.        btn.setText("message from main thread self");
  38.        btn.setOnClickListener(this);
  39.        LinearLayout.LayoutParams param =
  40.          new LinearLayout.LayoutParams(250,50);
  41.        param.topMargin = 10;
  42.        layout.addView(btn, param);
  43.        btn2 = new Button(this);
  44.        btn2.setId(102);
  45.        btn2.setText("message from other thread to main thread");
  46.        btn2.setOnClickListener(this);
  47.        layout.addView(btn2, param);
  48.        btn3 = new Button(this);
  49.        btn3.setId(103);
  50.        btn3.setText("message to other thread from itself");
  51.        btn3.setOnClickListener(this);
  52.        layout.addView(btn3, param);
  53.        btn4 = new Button(this);
  54.        btn4.setId(104);
  55.        btn4.setText("message with Runnable as callback from other thread to main thread");
  56.        btn4.setOnClickListener(this);
  57.        layout.addView(btn4, param);
  58.        btn5 = new Button(this);
  59.        btn5.setId(105);
  60.        btn5.setText("main thread's message to other thread");
  61.        btn5.setOnClickListener(this);
  62.        layout.addView(btn5, param);
  63.        btn6 = new Button(this);
  64.        btn6.setId(106);
  65.        btn6.setText("exit");
  66.        btn6.setOnClickListener(this);
  67.        layout.addView(btn6, param);
  68.        tv = new TextView(this);
  69.        tv.setTextColor(Color.WHITE);
  70.        tv.setText("");
  71.        LinearLayout.LayoutParams param2 =
  72.           new LinearLayout.LayoutParams(FP, WC);
  73.        param2.topMargin = 10;
  74.        layout.addView(tv, param2);
  75.        setContentView(layout);    
  76.       
  77.        //主线程要发送消息给other thread, 这里创建那个other thread
  78.    receiveMessageThread = new ReceiveMessageThread();
  79.    receiveMessageThread.start();
  80. }
  81. //implement the OnClickListener interface
  82. @Override
  83. public void onClick(View v) {
  84.    switch(v.getId()){
  85.    case 101:
  86. //主线程发送消息给自己
  87. Looper looper;
  88. looper = Looper.myLooper();   //get the Main looper related with the main thread
  89. //如果不给任何参数的话会用当前线程对应的Looper(这里就是Main Looper)为Handler里面的成员mLooper赋值
  90. mHandler = new EventHandler(looper);
  91. //mHandler = new EventHandler();
  92. // 清除整个MessageQueue里的消息
  93. mHandler.removeMessages(0);
  94. String obj = "This main thread's message and received by itself!";
  95. //得到Message对象
  96. Message m = mHandler.obtainMessage(1, 1, 1, obj);
  97. // 将Message对象送入到main thread的MessageQueue里面
  98. mHandler.sendMessage(m);
  99. break;
  100.    case 102:
  101. //other线程发送消息给主线程
  102. postRunnable = false;
  103. noLooerThread = new NoLooperThread();
  104. noLooerThread.start();
  105. break;
  106.    case 103:  
  107. //other thread获取它自己发送的消息
  108. tv.setText("please look at the error level log for other thread received message");
  109. ownLooperThread = new OwnLooperThread();
  110. ownLooperThread.start();
  111. break;
  112.    case 104:    
  113. //other thread通过Post Runnable方式发送消息给主线程
  114. postRunnable = true;
  115. noLooerThread = new NoLooperThread();
  116. noLooerThread.start();
  117. break;
  118.    case 105:    
  119. //主线程发送消息给other thread
  120. if(null!=mOtherThreadHandler){
  121. tv.setText("please look at the error level log for other thread received message from main thread");
  122. String msgObj = "message from mainThread";
  123. Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);
  124. mOtherThreadHandler.sendMessage(mainThreadMsg);
  125. }
  126. break;
  127.    case 106:
  128. finish();
  129. break;
  130.    }
  131. }
  132. class EventHandler extends Handler
  133. {
  134.    public EventHandler(Looper looper) {
  135. super(looper);
  136.    }
  137.    public EventHandler() {
  138. super();
  139.    }
  140.    public void handleMessage(Message msg) {
  141. //可以根据msg.what执行不同的处理,这里没有这么做
  142. switch(msg.what){
  143. case 1:
  144. tv.setText((String)msg.obj);
  145. break;
  146. case 2:
  147. tv.setText((String)msg.obj);
  148. noLooerThread.stop();
  149. break;
  150. case 3:
  151. //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
  152. Log.e(sTag, (String)msg.obj);
  153. ownLooperThread.stop();
  154. break;
  155. default:
  156. //不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
  157. Log.e(sTag, (String)msg.obj);
  158. break;
  159. }
  160.    }
  161. }
  162. //NoLooperThread
  163. class NoLooperThread extends Thread{
  164.    private EventHandler mNoLooperThreadHandler;
  165.    public void run() {
  166. Looper myLooper, mainLooper;
  167. myLooper = Looper.myLooper();
  168. mainLooper = Looper.getMainLooper(); //这是一个static函数
  169. String obj;
  170. if(myLooper == null){
  171. mNoLooperThreadHandler = new EventHandler(mainLooper);
  172. obj = "NoLooperThread has no looper and handleMessage function executed in main thread!";
  173. }
  174. else {
  175. mNoLooperThreadHandler = new EventHandler(myLooper);
  176. obj = "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!";
  177. }
  178. mNoLooperThreadHandler.removeMessages(0);
  179. if(false == postRunnable){
  180. //send message to main thread
  181. Message m = mNoLooperThreadHandler.obtainMessage(2, 1, 1, obj);
  182. mNoLooperThreadHandler.sendMessage(m);
  183. Log.e(sTag, "NoLooperThread id:" + this.getId());
  184. }else{
  185. //下面new出来的实现了Runnable接口的对象中run函数是在Main Thread中执行,不是在NoLooperThread中执行
  186. //注意Runnable是一个接口,它里面的run函数被执行时不会再新建一个线程
  187. //您可以在run上加断点然后在eclipse调试中看它在哪个线程中执行
  188. mNoLooperThreadHandler.post(new Runnable(){  
  189.     @Override  
  190.     public void run() {  
  191.    tv.setText("update UI through handler post runnalbe mechanism!");
  192.    noLooerThread.stop();
  193.     }  
  194. });  
  195. }
  196.    }
  197. }
  198. //OwnLooperThread has his own message queue by execute Looper.prepare();
  199. class OwnLooperThread extends Thread{
  200.    private EventHandler mOwnLooperThreadHandler;
  201.    public void run() {
  202. Looper.prepare();
  203. Looper myLooper, mainLooper;
  204. myLooper = Looper.myLooper();
  205. mainLooper = Looper.getMainLooper(); //这是一个static函数
  206. String obj;
  207. if(myLooper == null){
  208. mOwnLooperThreadHandler = new EventHandler(mainLooper);
  209. obj = "OwnLooperThread has no looper and handleMessage function executed in main thread!";
  210. }
  211. else {
  212. mOwnLooperThreadHandler = new EventHandler(myLooper);
  213. obj = "This is from OwnLooperThread self and handleMessage function executed in NoLooperThread!";
  214. }
  215. mOwnLooperThreadHandler.removeMessages(0);
  216. //给自己发送消息
  217. Message m = mOwnLooperThreadHandler.obtainMessage(3, 1, 1, obj);
  218. mOwnLooperThreadHandler.sendMessage(m);
  219. Looper.loop();
  220.    }
  221. }
  222. //ReceiveMessageThread has his own message queue by execute Looper.prepare();
  223. class ReceiveMessageThread extends Thread{
  224.    public void run() {
  225. Looper.prepare();
  226. mOtherThreadHandler = new Handler(){
  227. public void handleMessage(Message msg) {
  228.     Log.e(sTag, (String)msg.obj);
  229. }
  230. };
  231. Looper.loop();
  232.    }
  233. }
  234. }

 

 

使用Looper.myLooper静态方法可以取得当前线程的Looper对象。

使用mHandler = new EevntHandler(Looper.myLooper()); 可建立用来处理当前线程的Handler对象;其中,EevntHandler是Handler的子类。

使用mHandler = new EevntHandler(Looper.getMainLooper()); 可建立用来处理main线程的Handler对象;其中,EevntHandler是Handler的子类。



1.5.1.


主线程给自己发送消息示例


主线程发送消息





onClick


的case
101中创建一个继承自Handler的EventHandler对象,然后获取一个消息,然后通过EventHandler对象调用
sendMessage把消息发送到主线程的MessageQueue中。主线程由系统创建,系统会给它建立一个Looper对象和
MessageQueue,所以可以接收消息。这里只要根据主线程的Looper对象初始化EventHandler对象,就可以通过
EventHandler对象发送消息到主线程的消息队列中。

主线程处理消息:

这里是通过EventHandler的handleMessage函数处理的,其中收到的Message对象中what值为一的消息就是发送给它的,然后把消息里面附带的字符串在TextView上显示出来。


1.5.2.


其他线程给主线程发送消息示例


其他线程发送消息(这里是说不使用Runnable作为callback的消息):

首先
postRunnable设为false,表示不通过Runnable方式进行消息相关的操作。然后启动线程noLooerThread,
然后以主线程的Looper对象为参数建立EventHandler的对象mNoLooperThreadHandler,然后获取一个Message并
把一个字符串赋值给它的一个成员obj,然后通过mNoLooperThreadHandler把消息发送到主线程的MessageQueue中。

主线程处理消息:

这里是通过EventHandler的handleMessage函数处理的,其中收到的Message对象中what值为二的消息就是上面发送给它的,然后把消息里面附带的字符串在TextView上显示出来。


1.5.3.


其他线程给自己发送消息示例


其他线程发送消息:

其他非主线程建立后
没有自己的Looper对象,所以也没有MessageQueue,需要给非主线程发送消息时需要建立MessageQueue以便接收消息。下面说明如
何给自己建立MessageQueue和Looper对象。从OwnLooperThread的run函数中可以看见有一个
Looper.prepare()调用,这个就是用来建立非主线程的MessageQueue和Looper对象的。

所以这里的发送消息
过程是建立线程mOwnLooperThread,然后线程建立自己的Looper和MessageQueue对象,然后根据上面建立的Looper对象
建立对应的EventHandler对象mOwnLooperThreadHandler,然后由mOwnLooperThreadHandler建立消
息并且发送到自己的MessageQueue里面。

其他线程处理接收的消息:

线程要接收消息需要
在run函数中调用Looper.loop(),然后loop函数会从MessageQueue中取出消息交给对应的Handler对象
mOwnLooperThreadHandler处理,在mOwnLooperThreadHandler的handleMessage函数中会把
Message对象中what值为三的消息(上面发送的消息)在Log中打印出来,可以通过Logcat工具查看log。



1.5.4.


其他线程以


Runnable


为消息参数给主线程发送消息示例


其他线程发送消息(这里是说使用Runnable作为callback的消息):

首先
postRunnable设为true,表示通过Runnable方式进行消息相关的操作。然后启动线程noLooerThread,
然后以主线程的Looper对象为参数建立EventHandler的对象mNoLooperThreadHandler,然后获取一个Message并
把一个字符串赋值给它的一个成员obj,然后通过mNoLooperThreadHandler把消息发送到主线程的MessageQueue中。

主线程处理消息:

主线程收到上面发送的Message后直接运行上面Runnable对象中的run函数进行相应的操作。run函数通过Log打印一个字符串,可以通过Logcat工具查看log。


1.5.5.


主线程给其他线程发送消息示例


主线程发送消息




里首先要求线程receiveMessageThread运行(在onCreate函数中完成),并且准备好自己的Looper和
MessageQueue(这个通过ReceiveMessageThread中的run函数中的Looper.prepare()调用完成),然后根据
建立的Looper对象初始化Handler对象mOtherThreadHandler。然后在onClick的case
105中由mOtherThreadHandler建立一个消息(消息中有一个字符串对象)并且发送到线程receiveMessageThread中的
MessageQueue中。


其他线程处理接收的消息:

线程要接收消息需要在run函数中调用Looper.loop(),然后loop函数会从MessageQueue中取出消息交给对应的Handler对象

mOtherThreadHandler

处理,在

mOtherThreadHandler


的handleMessage函数中会把Message对象中的字符串对象在Log中打印出来,可以通过Logcat工具查看log。

抱歉!评论已关闭.