两个Handler,一个是主线程的mainHandler,一个是获取HandlerThread的looper的Handler.
mainHandler在新线程发出消息,在主线程处理接受的消息。
looperHandler拥有looper后即可post(Runnable),发起新线程,然后通过mainHandler在新线程里发送消息到主线程的handler。
这里创建两个handler,一个是mainHandler维护主线程的looper,一个是looperHandler拥护HandlerThread的looper。
1.mainHandler处理消息,复写handlerMessage()方法处理消息。
2.looperHandler应通过HandlerThread获取looper来构造,而且HandlerThread必须开启,否则得不到looper。
3.looperHandler来post一个runnable对象,在runnable里复写run()方法,在里面用mainHandler发送方消息。
1 package com.bvin.handler; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Handler; 6 import android.os.HandlerThread; 7 import android.os.Message; 8 import android.util.Log; 9 import android.view.View; 10 import android.widget.Button; 11 import android.widget.LinearLayout; 12 import android.widget.LinearLayout.LayoutParams; 13 import android.widget.TextView; 14 15 public class MainActivity extends Activity { 16 /** Called when the activity is first created. */ 17 18 private Handler loopHandler ; 19 private Handler mainHandler; 20 private TextView tv; 21 @Override 22 public void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 25 initViews(); 26 HandlerThread ht = new HandlerThread("handler thread"); 27 ht.start();//loopHandler的runnable这里先开始le,而mainHandler是点击之后 28 loopHandler = new Handler(ht.getLooper()); 29 mainHandler= new Handler(){ 30 31 @Override 32 public void handleMessage(Message msg) { 33 // TODO Auto-generated method stub 34 super.handleMessage(msg); 35 if(msg.what==2012){ 36 37 tv.setText(msg.getData().getString("s")); 38 } 39 40 } 41 }; 42 } 43 44 45 private void initViews(){ 46 47 LinearLayout layout = new LinearLayout(this); 48 layout.setOrientation(LinearLayout.VERTICAL); 49 LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); 50 tv = new TextView(this); 51 tv.setText("本来"); 52 Button bt = new Button(this); 53 54 bt.setText("开动"); 55 bt.setOnClickListener(new View.OnClickListener() { 56 57 @Override 58 public void onClick(View v) { 59 // TODO Auto-generated method stub 60 mainHandler.post(new Runnable(){ 61 62 @Override 63 public void run() { 64 // TODO Auto-generated method stub 65 Log.e("mainHandler所在当前线程", ""+Thread.currentThread().getName()); 66 //tv.setText("对不对"); 67 } 68 }); 69 70 loopHandler.post(new Runnable(){ 71 72 @Override 73 public void run() { 74 // TODO Auto-generated method stub 75 Log.e("loopHandler所在当前线程", ""+Thread.currentThread().getName()); 76 Message msg = mainHandler.obtainMessage(); 77 msg.what = 2012; 78 Bundle bundle = new Bundle(); 79 bundle.putString("s", "从"+Thread.currentThread().getName()+"线程传过来的"); 80 msg.setData(bundle); 81 msg.sendToTarget(); 82 } 83 }); 84 85 } 86 }); 87 layout.addView(bt,params); 88 layout.addView(tv,params); 89 setContentView(layout); 90 91 } 92 }