如何使用Handler实现主线程往子线程传递消息
myThread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (handler == null) {
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
myHandler.sendEmptyMessage(1);
Looper.loop();
Log.e("", "这是消息循环开始之后的代码");
}
}
});
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycle();
}
}
myThread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (handler == null) {
Looper.prepare();
handler = new Handler(Looper.myLooper()){//这里加上
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case do_some_th:break;
}
}
};
myHandler.sendEmptyMessage(1);
Looper.loop();
Log.e("", "这是消息循环开始之后的代码");
}
}
});
//主线程给子线程发消息:
在主线程里面调用handler.sendEmptyMessage(do_some_th);就可以执行了。
[解决办法]
哥们看下 这篇文章或许会帮到你。
http://blog.csdn.net/heng615975867/article/details/9194219
写在Looper.loop()之后的代码不会被执行,这个函数内部是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。