Android: one handler for all runnables?

送分小仙女□ 提交于 2019-12-10 01:31:43

问题


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


回答1:


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....
        }
    }  
   };



回答2:


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.



来源:https://stackoverflow.com/questions/9274265/android-one-handler-for-all-runnables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!