Android: one handler for all runnables?

2019-04-19 06:49发布

Can I use one handler in my Activity for all runnables or should I have multiple instances of Handler, each for one runnable?

2条回答
三岁会撩人
2楼-- · 2019-04-19 07:10

You can use only one handler and to specify from where your are coming use different message.

handler.sendEmptyMessage(messagevalue);  //use this to send message from different place

Now handle message

    private Handler handler=new Handler(){

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //specify msg value
        if(msg.what==10){
            //do this
        }else if(msg.what==20){
            // do this
        }else{
            //so on....
        }
    }  
   };
查看更多
干净又极端
3楼-- · 2019-04-19 07:14

I would say, that you should have one handler per thread (not per runnable), unless you do not need completely different behavior for different kinds of runnables.

查看更多
登录 后发表回答