标签:
一、Handler
Handler在android里负责发送和处理消息。它的主要用途有:
1)按计划发送消息或执行某个Runnanble(使用POST方法);HandlerThread继承于Thread,所以它本质就是个Thread。与普通Thread的差别就在于,它有个Looper成员变量。这个Looper其实就是对消息队列以及队列处理逻辑的封装,简单说就是 消息队列+消息循环。
当我们需要一个工作者线程,而不是把它当作一次性消耗品,用过即废弃的话,就可以使用它。
package com.android.settings;
}
package com.android.settings;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
/**
* Created by dev on 11/25/13.
*/
public class MyHandlerThread {
private HandlerThread mHandlerThread = null;
private MyHandler mHandler = null;
private Handler mMainHandler = null;
public MyHandlerThread(String threadName) {
super();
mHandlerThread = new HandlerThread(threadName);
mHandlerThread.start();
mHandler = new MyHandler(mHandlerThread.getLooper());
}
public void setmMainHandler(Handler handler) {
this.mMainHandler = handler;
}
public void sendMessage(Message msg) {
mHandler.sendMessage(msg);
}
class MyHandler extends Handler {
MyHandler() {
}
MyHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Message toMainMsg = mMainHandler.obtainMessage();
Log.d("tianxuhong","toMainMsg="+toMainMsg);
toMainMsg.what = 2;
Bundle bundle = new Bundle();
String threadID = String.valueOf(Thread.currentThread().getId());
String threadName = Thread.currentThread().getName();
bundle.putString("id", threadID);
bundle.putString("name", threadName);
toMainMsg.setData(bundle);
mMainHandler.sendMessage(toMainMsg);
}
}
}
android handler HandlerThread 用法
标签:
原文地址:http://blog.csdn.net/tianxuhong/article/details/42079227