当你创建一个thread,并且想在里面处理消息时:
方案一
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HandlerThread backgroudLoadThread =
new HandlerThread( "ConversationLoader", Process.
THREAD_PRIORITY_BACKGROUND );
backgroudLoadThread.start();
mLoadHandler =
new LoadHandler(backgroudLoadThread.get Looper());
}
/*解释:当你create一个handler时,它会和创建它的那个线程的messagequeue绑定。所以,当你想让它在子线程处理消息时,需要把子线程的looper传给它。另外,Handler还能处理Runable!!*/
protected void onDestroy() {
super .onDestroy();
if (mLoadHandler !=
null && mLoadHandler.get Looper() !=
null) {
mLoadHandler .getLooper().quit();
}
}
private class LoadHandler
extends Handler {
public LoadHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what ) {
case
MSG_INIT_QUERY :
initQuery();
break;
case
MSG_MAIN_QUERY :
if(mMainQueryId != -1){
MtcLog.
Mtc_LogsQryGrpLstByHasContact(mMainQueryId);
}
break;
case
MSG_SUB_QUERY :
if(mSubQueryId != -1){
MtcLog.
Mtc_LogsQryGrpLstByHasNoContact(mSubQueryId);
}
break;
case
MSG_MERGE_CONV :
mergeConversations();
break;
default:
break;
}
}
}
...
mLoadHandler .sendEmptyMessage(
MSG_INIT_QUERY);
方案二
public Handler mHandler;
class LooperThread extends Thread {
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}}
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}}
2.1 用Message.obtain
Message message = Message.
obtain(activity.getHandler(), R.id.
decode_failed);
message.sendToTarget();
/*
While the constructor of Message is public, the best way to get one of these is to call
Message.obtain() or one of the
Handler.obtainMessage() methods, which will pull them from a pool of recycled objects.
最好的获取Message的方式是调用obtain或obtainMessage,这样能从一个pool中拿到回收后的对象*/
2.2 直接用mHandler.sendMessage
另外,这种方式也需要quit,
Message quit = Message.
obtain(decodeThread.getHandler(), R.id.
quit);
quit.sendToTarget();
当你想在UI线程处理东西时
你可以在UI线程发消息给它,也可以在子线程发消息给它。
UI线程的Handler的Looper无需Quit,UI线程会自己做的。