Android消息处理机制(二)

Android消息处理机制()

角色综述(回顾):

   (1)UI thread 通常就是main thread,而Android启动程序时会替它建立一MessageQueue

(2)然需要一Looper对象,管理MessageQueue

(3)可以构造Handler对象push息到Message Queue;或者接收Looper(Message Queue取出)所送息。

(4)线AHandler对象可以传递给别线程,让别线BC等能送来给线A(存于AMessage Queue)

(5)线AMessage Queue息,只有线A的对象可以理。

 

子线程传递消息给主线程

public class Activity2 extends Activity implements OnClickListener{

       Button button = null;

       TextView text = null;

       MyHandler mHandler = null;

       Thread thread ;

       @Override

       protected void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.activity1);        

              button = (Button)findViewById(R.id.btn);

              button.setOnClickListener(this);

              text = (TextView)findViewById(R.id.content);

       }

       public void onClick(View v) {

              switch (v.getId()) {

              case R.id.btn:

                     thread = new MyThread();

                     thread.start();

                     break;

              }            

       }     

       private class MyHandler extends Handler{             

              public MyHandler(Looper looper){

                     super(looper);

              }

              @Override

              public void handleMessage(Message msg) {//处理消息

                     text.setText(msg.obj.toString());

              }            

       }

       private class MyThread extends Thread{

              @Override

              public void run() {

                     Looper curLooper = Looper.myLooper();

                     Looper mainLooper = Looper.getMainLooper();

                     String msg ;

                     if(curLooper==null){

                            mHandler = new MyHandler(mainLooper);

                            msg = "curLooper is null";

                     }else{

                            mHandler = new MyHandler(curLooper);

                            msg = "This is curLooper";

                     }

                     mHandler.removeMessages(0);

                     Message m = mHandler.obtainMessage(1, 1, 1, msg);

                     mHandler.sendMessage(m);

              }            

       }

}

说明:

Android替主线程建立Message Queue。在这个线里并没有建立Message Queue。所以,myLoopernull,而mainLooper指向主线Looper。于是,行到:

mHandler = new MyHandler (mainLooper);

mHandler于主线程。

   mHandler.sendMessage(m);

m息存入到主线程的Message QueuemainLooper看到Message Queue,就会作出处理,于是由主线行到mHandlerhandleMessage()来处息。

下一节将会写一个关于应多线程请求网络数据的例子。

你可能感兴趣的:(android)