我正在使用异步来更改我的 Activity 的 View ,以便我的屏幕在加载时不会卡住。我使用 HTTP get 来获取图像,这会减慢速度。我希望 http get 在后台运行,然后在完成后更改布局而不卡住应用程序。这是到目前为止我的代码:
public class BackgroundStuff extends AsyncTask<Data,Integer, Long> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Long doInBackground(Data... params) {
params[0].activity.updateUIGameOne(params[0].data);
publishProgress();
return null;
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
}
}
其中Data保存了MainActivity实例的值(其中布局正在改变)和http get代码实例的集合。
此代码 (updateUIGameOne) 在 MainActivity 上运行,但会卡住屏幕,直到完成该方法。
每当我运行 BackgoundStuff AsyncTast 时,我都会收到异常“只有创建 View 层次结构的原始线程才能触摸其 View ”
我应该如何运行这个在后台更改 View 而不卡住屏幕的方法?
最佳答案
该错误是不言自明的:您在 doInBackground() 中执行的所有操作都发生在后台线程中。您只能从主线程更新您的 UI。
您想要做的是在 doInBackground()
中执行长时间运行的操作,例如网络请求,然后在 onPostExecute()
中更新您的 UI。
关于java - Android:编辑 View 的异步任务给出 "Only the original thread that created a view hierarchy can touch its views"(HTTPGet 卡住应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30518060/