gpt4 book ai didi

java - 在Android 11中弃用了Android AsyncTask API,使用了Executor作为替代

转载 作者:行者123 更新时间:2023-12-03 13:06:12 28 4
gpt4 key购买 nike

我正在使用下面的代码在后台和后执行中运行,但是我的问题是,我如何像以前在AsyncTask中那样执行onPrexecute,例如能够设置可见的进度条运行:
我到目前为止使用的代码,但是UI出现错误:

    ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());

executor.execute(new Runnable() {
@Override
public void run() {

//Background work here
progressBar_main_activity.setVisibility(View.VISIBLE);
runbackground();

handler.post(new Runnable() {
@Override
public void run() {
//UI Thread work here
update_UI();
}
});
}
});
错误在这里“progressBar_main_activity.setVisibility(View.VISIBLE);”
错误如下:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.         at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:8205)         at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1426)

最佳答案

ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());

//onPreExecute() before to get into executor, as below
progressBar_main_activity.setVisibility(View.VISIBLE);


executor.execute(new Runnable() {
@Override
public void run() {

//Background work here
runbackground();

handler.post(new Runnable() {
@Override
public void run() {
//UI Thread work here
update_UI();
}
});
}
});

关于java - 在Android 11中弃用了Android AsyncTask API,使用了Executor作为替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66715301/

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