當我開始我的一項活動時,我希望它能夠訪問多個網頁並從那裏下載東西(包括約8000行Json)。所有這些代碼都需要一段時間。目前代碼都是這樣的。在gui中加載代碼
@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實際上並沒有顯示出來,直到它在text.setText(「Downloading update ..」)行之後。 當我搜索一個有關如何做一些更多的信息,我發現這個圖片: http://developer.android.com/images/activity_lifecycle.png
我幾乎知道,我不希望它在運行的onCreate,因爲這將需要很長時間才能拿到GUI。 onStart或onResume也不可能,因爲我不希望它每次開始活動時下載8000+行文件。
那麼我應該在哪裏運行此代碼? (UpdateChecker和UpdateMods爲2個ASyncTasks)
如果你在你的Activity類中定義了你的AsyncTask,那麼你可以更新你的gui,當onPostExecute被AsyncTask調用時 – edoardotognoni 2013-04-30 15:06:18
如果你在執行後立即立即調用get(),那麼asynctask有什麼意義? – njzk2 2013-04-30 15:28:25
我無法將任何一個ASyncs的代碼放置在Activity代碼中,因爲它使用的URL不能在主線程中完成,並且必須位於ASync中。 – Wuppy29 2013-04-30 19:21:22