我正在使用Async来改变我的活动视图,这样我的屏幕就不会在加载时冻结。我使用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);
}
}
其中数据保存MainActivity实例(其中布局正在改变)的值和http get代码实例的集合。
这段代码(updateUIGameOne)在MainActivity上运行,但会冻结屏幕,直到它完成该方法。
每当我运行BackgoundStuff AsyncTast时,我都会得到异常“只有创建视图层次结构的原始线程才能接触到它的视图”。
如何在不冻结屏幕的情况下运行这个在后台更改视图的方法?
发布于 2015-05-28 22:26:22
这个错误是不言而喻的:您在doInBackground()
中所做的一切都发生在后台线程中。您只能从主线程更新您的UI。
您要做的是在doInBackground()
中执行长期运行的操作,比如网络请求,然后在onPostExecute()
中更新您的UI。
发布于 2015-05-28 22:28:48
您应该将UI代码放在runOnUiThread中
runOnUiThread(new Runnable(){
public void run() {
updateUI();
}
});
https://stackoverflow.com/questions/30518060
复制相似问题