java - Android:编辑 View 的异步任务给出 "Only the original thread that created a view hierarchy can touch its views"(HTTPGet 卡住应用程序)

标签 java android multithreading android-asynctask

我正在使用异步来更改我的 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/

相关文章:

Java 运行异步进程

java - Future.cancel(true) 下发生了什么

只返回我想要的某些元素的Java Http请求

android - 从 arduino 到 android 的直接串行端口连接用于数据通信

c - Pthreads - 高内存使用率

android - 为什么 getLastLocation 返回 null?

android - 如何在 Caldroid 日历中禁用直到今天的所有日期?

java - Cassandra CQL表INSERT和INDEX问题

java - 删除那些属性不在 commons-collections 集合中的属性

java - log4j 可以配置为使用 Joda Time 的时区数据库吗?