package com.handler.exa1;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Android_Handler_1 extends Activity implements OnClickListener {
private Handler hdr;
private Timer timer= new Timer();
private int iCount=0;
private Handler testMQHandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn;
btn= (Button)this.findViewById(R.id.Btn_runsvr);
btn.setOnClickListener(this);
btn= (Button)this.findViewById(R.id.Btn_Finish);
btn.setOnClickListener(this);
btn= (Button)this.findViewById(R.id.Btn_Runnable);
btn.setOnClickListener(this);
btn= (Button)this.findViewById(R.id.Btn_doTest);
btn.setOnClickListener(this);
hdr= new Handler(){
@Override
public void handleMessage(Message msg) {
setTitle((String)msg.obj);
}
};
//产生测试线程。
new testThread().start();
}
@Override
public void onClick(View v) {
int idx= v.getId();
switch (idx)
{
case R.id.Btn_Finish:
this.finish();
break;
case R.id.Btn_Runnable:
new MyThread().start();
break;
case R.id.Btn_doTest:
testMQHandler.removeMessages(0); //clear all messages in MQ
Message msg= testMQHandler.obtainMessage(1, 1, 1, "btn_doText clicked");
testMQHandler.sendMessage(msg);
break;
case R.id.Btn_runsvr:
/* //直接自己投递给自己
hdr.removeMessages(0); //clear all messages in MQ
Message msg= hdr.obtainMessage(1, 1, 1, "Message via handler");
hdr.sendMessage(msg);
*/
//在定时器线程中投递给主线程
TimerTask task= new TimerTask() {
@Override
public void run() {
hdr.removeMessages(0); //clear all messages in MQ
Message msg= hdr.obtainMessage(1, 1, 1, "Message order:" + String.valueOf(iCount++));
hdr.sendMessage(msg);
}
};
timer.schedule(task, 500, 1000); //每秒执行一次
break;
}// end switch
}
class MyThread extends Thread {
@Override
public void run() {
//方式一, 把 runnable interface 附加到主线程执行。
hdr.post(new MyRunnable("Post Runnable"));
/* //方式二,直接使用SendMessage + Message
String obj = "from myThread...";
Message m = hdr.obtainMessage(1, 1, 1, obj);
hdr.sendMessage(m);
*/
}
}
class MyRunnable implements Runnable {
private String obj;
MyRunnable(String o) {
obj= o;
}
@Override
public void run() {
setTitle(obj);
}
}
/*
* 主线程投递到子线程的实现。
* 主线程产生子线程,子线程产生自己的MQ后把Handler报给主线程
* 主线程投递信息给子线程,子线程处理完在投递给主线程
*/
class testThread extends Thread {
//Looper testLooper, MainLooper;
@Override
public void run() {
//testLooper= Looper.myLooper(); //本句产生线程自身的looper。
//MainLooper= Looper.getMainLooper(); //获得主线程的looper。
//hdr= new Handler(MainLooper);
Looper.prepare();
testMQHandler= new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i("just in testThread", (String)msg.obj);
}
}; //获取操作线程自身MQ的handler
Looper.loop();
}
}
}
- 1
- 2
- 3
- 4
前往页