gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 08:03:46 25 4
gpt4 key购买 nike

有人可以向我解释如何使用 switchwhat 字段来确定要执行的代码。此外,如何创建要在开关中使用的消息对象也很棒。

我的处理程序代码示例:

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

}
}
};

最佳答案

如果您正在使用处理程序,我假设您想在不同的线程中做一些工作,并且正在使用处理程序与您正在启动的线程和主线程进行 b/w 通信。举个例子:

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

希望这对您有所帮助。

关于java - 你如何使用消息类中的 what 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17257395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com