当然我们也可以隐式的指定Looper ,代码如下:
?[Copy to clipboard]
Download zuiniuwang.java
- /**
- * MessageQueue2.java
- * com.test
- *
- * Function: TODO
- *
- * ver date author
- * ──────────────────────────────────
- * 2011-3-20 Leon
- *
- * Copyright (c) 2011, TNT All Rights Reserved.
- */
- package com.test.messagequeue;
- /**
- * ClassName:MessageQueue2
- * Function: TODO ADD FUNCTION
- * Reason: TODO ADD REASON
- *
- * @author Leon
- * @version
- * @since Ver 1.1
- * @Date 2011-3-20
- */
- 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;
- public class MessageQueue3 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, btn3;
- private EHandler mHandler;
- 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.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.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:
- // mHandler = new EHandler(Looper.myLooper());
- //可以隐式的制定Looper,和上面的效果是一样的
- mHandler = new EHandler();
- t = new myThread();
- t.start();
- break;
- case 102:
- finish();
- break;
- }
- }
- //------------------------------------------------------
- class EHandler extends Handler {
- public EHandler(Looper looper) {
- super(looper);
- }
- public EHandler(){
- }
- @Override
- public void handleMessage(Message msg) {
- tv.setText((String)msg.obj);
- }
- }
- //------------------------------------------------------
- class myThread extends Thread{
- public void run() {
- String obj = "This message is from new thread.";
- mHandler.removeMessages(0);
- Message m = mHandler.obtainMessage(1, 1, 1, obj);
- mHandler.sendMessage(m);
- }
- }
在此代码中,指令:h = new EventHandler();就等于:h = new EventHandler(Looper.myLooper());
它建立了当前线程(Current Thread)的EventHandler对象。由于是由main线程执行此指令的,所以此EventHandler对象是用来存取main线程的Message Queue的。
本文转自 最牛傻蛋 51CTO博客,原文链接:http://blog.51cto.com/zuiniuwang/718338,如需转载请自行联系原作者