由別的線程送訊息到主線程的Message Queue
- package com.example.ac01;
- import android.app.Activity;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Looper;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.LinearLayout;
- import android.widget.TextView;
- //由別的線程送訊息到主線程的Message Queue
- public class ac02 extends Activity implements OnClickListener {
- private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
- private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
- public TextView tv;
- private myThread t;
- private Button btn, btn2;
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- LinearLayout layout = new LinearLayout(this);
- layout.setOrientation(LinearLayout.VERTICAL);
- btn = new Button(this);
- btn.setId(101);
- btn.setBackgroundResource(R.drawable.icon);
- btn.setText("test looper");
- btn.setOnClickListener(this);
- LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(100, 50);
- param.topMargin = 10;
- layout.addView(btn, param);
- btn2 = new Button(this);
- btn2.setId(102);
- btn2.setBackgroundResource(R.drawable.icon);
- btn2.setText("exit");
- btn2.setOnClickListener(this);
- layout.addView(btn2, 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);
- }
- public void onClick(View v) {
- switch (v.getId()) {
- case 101:
- t = new myThread();
- t.start();
- break;
- case 102:
- finish();
- break;
- }
- }
- // ------------------------------------------------------
- class EHandler extends Handler {
- public EHandler(Looper looper) {
- super(looper);
- }
- @Override
- public void handleMessage(Message msg) {
- tv.setText((String) msg.obj);
- }
- }
- // ------------------------------------------------------
- class myThread extends Thread {
- private EHandler mHandler;
- // Android會自動替主線程建立Message Queue
- // 在這個子線程裡並沒有建立Message Queue
- // 所以,myLooper值為null,而mainLooper則指向主線程裡的Looper物件
- public void run() {
- Looper myLooper, mainLooper;
- myLooper = Looper.myLooper();
- mainLooper = Looper.getMainLooper();
- String obj;
- if (myLooper == null) {
- // 此mHandler屬於主線程
- // 这里我们可以这样理解:因为根据demo1中的形象比喻,如果这个机构的传话员,跟这个Looper部门
- // 应该属于同一个线程才符合情理
- mHandler = new EHandler(mainLooper);
- obj = "current thread has no looper!";
- } else {
- mHandler = new EHandler(myLooper);
- obj = "This is from current thread.";
- }
- mHandler.removeMessages(0);
- Message m = mHandler.obtainMessage(1, 1, 1, obj);
- mHandler.sendMessage(m);
- }
- }
- }
- // -------------------------------------------------------
代码中已经做了很详细的解释,有疑问的我们可以一起探讨