我在運行一個AsyncTask
,它打開一個HttpConnection
並使用它在doInBackground
函數中下載JSON。Android ProgressDialog結束得太早
這裏是我的AsyncTask:
public class AsyncQueryTask extends AsyncTask<URL, Void, String>{
String jsonString = "";
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Getting Ready...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
}
@Override
protected String doInBackground(URL... urls) {
URL restURL = urls[0];
try {
//--------------------------------------------
// Some initialization
//--------------------------------------------
HttpURLConnection urlCon = (HttpURLConnection) restURL.openConnection();
InputStream in = urlCon.getInputStream();
Scanner scan = new Scanner(in).useDelimiter("\\A");
jsonString = scan.hasNext()? scan.next() : "";
try{
JSONArray bookArr = new JSONArray(jsonString);
for(int i=0;i<bookArr.length();i++){
// Some JSON string processing...
}
} catch(Exception e){
Log.e("Err", "@Activity");
e.printStackTrace();
}
//----------------------------------------------------
return jsonString;
} catch(IOException ioe){
ioe.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
}
}
而且我在這裏把它叫做:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
URL url = // URL for fetching JSON string
if (/*Some condition*/) {
//----------------------------------------------
// Some other tasks
//----------------------------------------------
AsyncQueryTask fbqt = new AsyncQueryTask();
fbqt.execute(url);
Intent intent = new Intent(context, NextActivity.class);
startActivity(intent);
}
}
正如你所看到的,我正確初始化progressDialog在onPreExecute()
,並dismiss()
它onPostExecute()
。
的問題是進度對話框顯示了只有一秒鐘的一小部分,它立即結束,從而導致應用程序轉移到下一個活動,在不doInBackground()
部分充分執行它的任務。
我應該怎麼做progressDialog直到doInBackground()
線程完成?
執行AsyncTask後,LoginActivity已經完成,下一個活動應該開始。如果我在AsyncTask執行後無法調用它,我應該在哪裏調用'startActivity()'函數? – JeobMallari
@JeobMallari,但你需要在asynck任務完成後啓動'NextActivity',對嗎?我的意思是你想等到它完成後再啓動'NextActivty'? –
@JeobMallari檢查這個[answer](http://stackoverflow.com/a/43690935/5993410) –