Android Handler用法

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.wv1124.adnroid.R;

public class HandleTestActivity extends Activity {

	Handler handler = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Log.d("DEBUG", "Activity-->" + Thread.currentThread().getId());

		// 生成一个HandlerThread对象,为了使Handler在此线程中执行;
		HandlerThread handlerThread = new HandlerThread("handler_thread") {
			@Override
			public void run() {
				Log.d("DEBUG", "handlerThread-->"
						+ Thread.currentThread().getId());
				super.run(); // 注意,不要重写;
			}
		};
		// 启动线程;
		handlerThread.start();

		//Looper p = Looper.myLooper(); //也可以使用主线程的Looper但会使主线程停止执行等待;	

		// handlerThread.getLooper()初始化Handler使Hander在handlerThread的程线中执行;
		handler = new Handler(handlerThread.getLooper()) {
			@Override
			public void handleMessage(Message msg) {
				Bundle b = msg.getData();
				int age = b.getInt("age");
				String name = b.getString("name");
				Log.d("DEBUG", "Handler-->" + Thread.currentThread().getId()
						+ " : age is " + age + ", name is" + name);
			}
		};

		// 可以这样发消息;
		// Message msg = handler.obtainMessage();
		// Bundle b = new Bundle();
		// b.putInt("age", 20);
		// b.putString("name", "Jhon");
		// msg.setData(b);
		// msg.sendToTarget();

		// 工作线程;
		Thread t = new Thread() {
			private int i = 0;

			@Override
			public void run() {
				Log.d("DEBUG", "work Thread-->"
						+ Thread.currentThread().getId() + " start;");
				Message msg = new Message();
				Bundle b = new Bundle();
				b.putInt("age", i++);
				b.putString("name", "Jhon" + i++);
				msg.setData(b);
				handler.sendMessage(msg); // 发消息给Handler所在的线程;
				if (i < 3) {
					handler.postDelayed(this, 30000); // 重复定时任务;
				}

				Log.d("DEBUG", "work Thread-->"
						+ Thread.currentThread().getId() + " exit;");
			}

			// 注意此方法没有在Handler被调用,Handler直接调用run方法;
			public synchronized void start() {
				Log.d("DEBUG", "work Thread start()");
				super.start();
			}
		};
		t.setName("work thread");
		t.start(); // 主线程中调用start()方法;

		// // 定时器功能;
		// Thread t = new Thread() {
		// @Override
		// public void run() {
		// Log.d("DEBUG", "*");
		// handler.postDelayed(this, 3000);
		// }
		// };
		// t.start();
		// Log.d("DEBUG", "t.start()");
	}
}

相关参考:

深入理解Android消息处理系统——Looper、Handler、Thread

相关推荐