这个例子是为了更进一步的理解Demo2
这个例子跟Demo2只是有些小的改动,大家可以对比的看下
这个例子跟Demo2只是有些小的改动,大家可以对比的看下
- package com.example.Looper_03;
- import android.app.Activity;
- import android.content.Context;
- 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 Looper_03 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;
- EventHandler h;
- Context ctx;
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- ctx = this;
- 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:
- // 此h是屬於main線程的(用來存取主線程的MessageQueue)
- //h = new EventHandler(Looper.myLooper());//@
- //或者可以写成这样;
- h = new EventHandler();
- t = new myThread();
- t.start();
- break;
- case 102:
- finish();
- break;
- }
- }
- //或者可以写成这样;
- public class EventHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- ((Activity) ctx).setTitle((String) msg.obj);
- }
- }
- // ------------------------------------------------
- /*public class EventHandler extends Handler {//@
- public EventHandler(Looper looper) {
- super(looper);
- }
- @Override
- public void handleMessage(Message msg) {
- ((Activity) ctx).setTitle((String) msg.obj);
- }
- }*/
- // ------------------------------------------------------
- class myThread extends Thread {
- public void run() {
- String obj = "from myThread";
- Message m = h.obtainMessage(1, 1, 1, obj);
- //这里还是通过主线程的handler来传送消息
- //所以还是由主线程的Looper来接受消息
- h.sendMessage(m);
- }
- }
- }
- // ------------------------------------------------------