gpt4 book ai didi

android - 将更新/数据从一个线程发送到 Android 中的 UI 线程

转载 作者:行者123 更新时间:2023-11-29 01:54:35 25 4
gpt4 key购买 nike

基于按钮点击,我必须做一些需要一些时间的处理。所以我决定在主 UI 线程之外的单独线程中执行此操作。

现在,根据单独线程中的计算,我在创建这个新线程的 UI 线程的主类中调用一个函数。在这个函数中,我更新了 UI。有人告诉我这行不通,因为我需要调用主 UI 线程。

有人可以帮我解决这个问题吗?

@Override
public void onListItemClicked(int index, Map<String, Object> data) {

new Thread(new Runnable() {
@Override
public void run() {
// Issue command() on a separate thread
wasCommandSuccess(command());
}
}).start();
}


private void wasCommandSuccess(boolean result){
if (result == false){
getUI(BasicUI.class).showAlert("Command failed!", "Unable to access");
}
}

最佳答案

您应该在 runOnUiThread() 中调用 wasCommandSuccess 函数;所以你应该有这样的代码:

@Override
public void onListItemClicked(int index, Map<String, Object> data) {

new Thread(new Runnable() {
@Override
public void run() {
// Issue command() on a separate thread
final boolean result = command();
// you need to pass your context (any of Activity/Service/Application) here before this
context.runOnUiThread(new Runnable() {
@Override
public void run() {
wasCommandSuccess(result);
}
});
}
}).start();
}


private void wasCommandSuccess(boolean result){
if (result == false){
getUI(BasicUI.class).showAlert("Command failed!", "Unable to access");
}
}

关于android - 将更新/数据从一个线程发送到 Android 中的 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15921789/

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