Handler不执行handleMessage方法

来源:互联网  时间:2016/6/3 17:39:20

关于网友提出的“Handler不执行handleMessage方法”问题疑问,本网通过在网上对“Handler不执行handleMessage方法”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题:Handler不执行handleMessage方法
描述:

public class BounceActivity extends Activity {
    protected static final int GUIUPDATEIDENTIFIER = 0x101;
    BounceView bounceView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.bounceView = new BounceView(this);
        this.setContentView(this.bounceView);
        handler.post(r);
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
   System.out.println("handle message");
            switch (msg.what){
                case BounceActivity.GUIUPDATEIDENTIFIER:
                    bounceView.invalidate();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    Runnable r = new Runnable() {
        @Override
        public void run() {
            while(!Thread.currentThread().isInterrupted()){
System.out.println("thread running");
                Message msg = handler.obtainMessage();
                msg.what = BounceActivity.GUIUPDATEIDENTIFIER;
                handler.sendMessage(msg);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    };
}

执行结果:每隔3s就打印一次thread running

疑问:在主线程中handler将r线程对象添加到消息队列,执行r线程时,handler.sendMessage(msg)向handler发送消息,为什么不执行handler的handleMessage()方法呢?

请大家多多指教,谢谢!





解决方案1:

Cara90说的才是对的,我的错鸟。。。

解决方案2:

因为handler在主线程中,handler.post(r)并不是单独开启一个新的线程,而是调用线程r对象run()方法,在run()方法里一直循环执行代码,所以只有run()方法执行完毕,handler才会执行handleMessage()方法来接收消息。

解决方案3:

看源代码, handleMessage 是放在callback接口中的,只有开启线程的时候,找个接口才被调用。所以,不开新线程,handleMessage 是不会被调用的。

上一篇Intellij IDEA免费版,如何在新建一个class的时候可以选择继承的父类和需要实现的接口
下一篇你的Intellij IDEA启动需要多久?
明星图片
相关文章
《Handler不执行handleMessage方法》由码蚁之家搜集整理于网络,
联系邮箱:mxgf168#qq.com(#改为@)