方法1通过普通Thread自己创建loop
class Thread1 extends Thread {
public void run() {
this.setName("Thread1");
// 初始化消息循环队列,需要在Handler创建之前
Looper.prepare();
m_Thread1Handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i("Thread1",
"Got an incoming message from the main thread - "
+ (String) msg.obj);
}
};
// 启动子线程消息循环队列
Looper.loop();
}
}
在界面销毁的时候需要调用
m_Thread1Handler.getLooper().quit();
方法2通过系统的HandlerThread
m_HandlerThread = new HandlerThread("Thread2");
// 开启一个线程
m_HandlerThread.start();
// 在这个线程中创建一个handler对象
m_Thread2Handler = new Handler(m_HandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i("Thread2",
"Got an incoming message from the main thread - "
+ (String) msg.obj);
}
};
下载