gpt4 book ai didi

java - 能够在 doInBackground 中更新 UI

转载 作者:太空狗 更新时间:2023-10-29 15:28:14 24 4
gpt4 key购买 nike

据我所知,我们无法通过 AsyncTask 的 doInBackground 方法更改 UI 元素,但在执行相同操作并更改 TextView 的文本时它不会给出任何异常。

 public class MainActivity extends Activity {

TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
Toast.makeText(MainActivity.this, "Main : " + Thread.currentThread().getName(), Toast.LENGTH_SHORT).show();
new DemoAsync().execute();
}

class DemoAsync extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... params) {
String threadName = "Async : " + Thread.currentThread().getName();
for(int i=0;i<1000;i++) {
tv.setText("Changed " + i);
}
return threadName;
}

@Override
protected void onPostExecute(String threadName) {
Toast.makeText(MainActivity.this, threadName, Toast.LENGTH_SHORT).show();
}
}
}

我尝试检查 doInBackground 是否在主线程中运行,但也不是这种情况。但是,在 doInbackground 中显示 Toast 时,应用程序崩溃了。修改 TextView 也应该使应用程序崩溃。有人可以解释这种行为吗?

P.S - 关于可能的重复,我在 pre lollipop 上运行代码,所以问题以及选择的答案与此无关。此外,答案表明修改 TextView 将在以后的调用中崩溃(第 18 到在选择答案的情况下要准确)。我已经更新了代码以在 1000 次迭代的循环中修改 TextView,它仍然运行良好。

最佳答案

Android "Processes and Threads" documentation 中所述,您不应从 doInBackground 访问 UI :

Do not access the Android UI toolkit from outside the UI thread

关于java - 能够在 doInBackground 中更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31115560/

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