目前,当我开始我的某个活动时,我希望它能够访问多个网页并从那里下载内容(包括大约8000行Json)。所有这些代码都花了很长时间。目前代码都是这样的。
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_mods);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
// gets ad from google
AdView adView = (AdView) this.findViewById(R.id.ad);
adView.loadAd(new AdRequest());
// prepare for a progress bar dialog
bar = (ProgressBar) (this.findViewById(R.id.progressBar1));
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
bar.setMinimumWidth((width / 5 * 2));
bar.setMax(3);
bar.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.toMods);
text.setText("Checking for updates...");
UpdateChecker update = new UpdateChecker();
update.execute(getBaseContext());
try
{
if (update.get() == true)
{
bar.setMax(5);
text.setText("Downloading update..");
UpdateMods updater = new UpdateMods();
updater.execute(getBaseContext());
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
}
现在的问题是,即使(据我所知)在text.setText("检查更新后)完成后,需要很长时间才能让Gui显示出来。 ..&#34) 然而,gui实际上并没有出现,直到text.setText(" Downloading update ..")行。 当我在搜索有关如何操作的更多信息时,我发现了这个图像: http://developer.android.com/images/activity_lifecycle.png
我几乎知道我不希望它在onCreate中运行,因为获取gui需要很长时间。也不可能在onStart或onResume上,因为每次开始活动时我都不希望它下载8000+行文件。
那么我应该在哪里运行此代码? (UpdateChecker和UpdateMods是2个ASyncTasks)
答案 0 :(得分:5)
你的问题在这里:
if (update.get() == true)
这就是说,实际上,“阻止主应用程序线程并冻结UI,直到doInBackground()
完成”。
摆脱那条线。相反,请根据onPostExecute()
AsyncTask
中任务的完成情况对您的用户界面进行修改。