怎么使用Handler实现主线程往子线程传递消息

 我来答
城南明月羿当年
2015-04-03 · 知道合伙人生活技巧行家
城南明月羿当年
知道合伙人生活技巧行家
采纳数:24666 获赞数:123229
计算机爱好者

向TA提问 私信TA
展开全部
------解决方案--------------------
Looper.loop(); 之后 需要做啥?

Lopper myLopper = null;
new Thread(){
public void run(){
Looper.prepare();
myLopper = Lopper.myLooper();
Looper.loop();
}
}.start();

class Threadhandler extends Handler {
public void handleMessage(Message msg) {

}

}
Threadhandler handler = new Threadhandler(myLopper);

------解决方案--------------------
楼主牛逼,这啥需求?语句执行到Looper.loop();后,线程会阻塞在这里,后面的语句根本无法执行。
除非让loop()消息循环退出(可以调用quit()函数),否则根本无法按照你的需求来实现。
/**

* 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();

}

}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式