如何使用Handler实现主线程往子线程传递消息

流星叶雨 2013-12-30 05:03:52

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("", "这是消息循环开始之后的代码");
}
}
});

如以上代码,如何能让Looper.loop();之后的代码执行呢?也就是说loop之后,不影响线程逻辑的执行~~~~求思路
...全文
628 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
jimzbq 2014-03-01
  • 打赏
  • 举报
回复
请问楼主是用的其他什么方法解决的啊。。。我也遇到这个问题了。。。
流星叶雨 2014-01-03
  • 打赏
  • 举报
回复
已经用其他方案解决该需求,感谢各位~~
流星叶雨 2014-01-02
  • 打赏
  • 举报
回复
引用 7 楼 ncepu307 的回复:
[quote=引用 4 楼 tf110012 的回复:] 就是说能不能实现这种效果,某个运行的线程里,可以随时接收或者监听其他线程发来的消息~~~~
怎么不可以?? 你的线程里不是实例化了一个个Handler对象handler么?在其他线程(比如主线程)中,调用handler.sendEmptyMessage()不就接收了其他线程发来的消息么?[/quote] 实例化后必须调用Looper.loop();handler才能收到其他线程发来的消息,但是Looper.loop();里面是一个循环,会导致Looper.loop();之后的代码不执行,这样我放在Looper.loop();之后的逻辑就不能执行了
依然绿茶 2014-01-02
  • 打赏
  • 举报
回复
引用 4 楼 tf110012 的回复:
就是说能不能实现这种效果,某个运行的线程里,可以随时接收或者监听其他线程发来的消息~~~~
怎么不可以?? 你的线程里不是实例化了一个个Handler对象handler么?在其他线程(比如主线程)中,调用handler.sendEmptyMessage()不就接收了其他线程发来的消息么?
酒比花香 2014-01-02
  • 打赏
  • 举报
回复
哥们看下 这篇文章或许会帮到你。 http://blog.csdn.net/heng615975867/article/details/9194219 写在Looper.loop()之后的代码不会被执行,这个函数内部是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。
流星叶雨 2014-01-02
  • 打赏
  • 举报
回复
引用 5 楼 lqgyt1 的回复:


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);就可以执行了。
不行啊,我想让Log.e("", "这是消息循环开始之后的代码");这句执行,而不是do_some_th哦,另外不能quit()looper,因为退出之后这个线程就无法继续监听主线程发来的消息了
流星叶雨 2013-12-31
  • 打赏
  • 举报
回复
就是说能不能实现这种效果,某个运行的线程里,可以随时接收或者监听其他线程发来的消息~~~~
流星叶雨 2013-12-31
  • 打赏
  • 举报
回复
引用 2 楼 ncepu307 的回复:
楼主牛逼,这啥需求?语句执行到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();
        }
    }
楼主蛋疼着- -也知道loop里面是一个循环,有消息就处理,无消息就挂起,所以想请教各位有没有啥方案解决,曲线救国也好啊~~~因为用了一个第三方框架,他的逻辑在一个单独的线程里,而且逻辑是一直执行的,就是说只要程序在运行,这个线程就在运行状态,楼主想在主线程中往这个线程里发消息~~~结果发现如上问题,无法初始化handler,不知道如何弄了
lqgyt1 2013-12-31
  • 打赏
  • 举报
回复


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);就可以执行了。
依然绿茶 2013-12-30
  • 打赏
  • 举报
回复
楼主牛逼,这啥需求?语句执行到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();
        }
    }
Birds2018 2013-12-30
  • 打赏
  • 举报
回复
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);

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧