你如何使用消息类中的what字段?

时间:2013-06-23 03:09:29

标签: java android

有人可以向我解释如何将switchwhat字段一起使用来确定要执行的代码。 另外,如何创建在交换机中使用的消息obj也很棒。

我的处理程序代码示例:

Handler uiHandler = new Handler(){
    public void handleMessage(Message msg){
        switch(msg.what){

        }
    }
};

2 个答案:

答案 0 :(得分:4)

如果您正在使用处理程序,我假设您希望在不同的线程中执行某些工作,并使用处理程序与您正在启动的线程和主线程进行通信。请看以下示例:

private static final int SUCCESS = 0;
private static final int FAIL = 1;

//This is the handler
Handler uiHandler = new Handler(){
    @Override
    public void handleMessage(Message msg){
        //Here is how you use switch statement
        switch(msg.what){
        case SUCCESS:
            //Do something      
            break;
        case FAIL:
            //Do something
            break;
        }

    }
};

//Here is an example how you might call it
Thread t = new Thread() {
    @Override
    public void run(){
        doSomeWork();
        if(succeed){
            /*we can't update the UI from here so we'll signal our handler 
             and it will do it for us.*/
            // 'sendEmptyMessage(what)' sends a Message containing only the 'what' value.
            uiHandler.sendEmptyMessage(SUCCESS);
        }else{
            uiHandler.sendEmptyMessage(FAIL);
        }
    }   
}

归功于这两个主题:它们可能是一个很好的阅读: Android: When should I use a Handler() and when should I use a Thread?& Android Handler actions not being processed

希望这会有所帮助。

答案 1 :(得分:0)

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {             
        case SECOND_VALUE:
            String s = (String) msg.obj;  // if msg.obj is a string
            break;

        case FIRST_VALUE:
            AnotherObject = (AnotherObject) msg.obj;   // if it is another object
            break;

        default:
            super.handleMessage(msg);
        }
    }