【发布时间】:2017-09-28 09:07:16
【问题描述】:
我正在运行一个AsyncTask,它打开一个HttpConnection 并使用它在doInBackground 函数中下载JSON。
这是我的异步任务:
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);
}
}
如您所见,我在onPreExecute() 中正确初始化了progressDialog,并在onPostExecute() 中正确初始化了dismiss()。
问题是进度对话框只显示了几分之一秒,它立即结束,导致应用程序转移到下一个活动,而没有完全执行它在doInBackground() 部分。
我应该怎么做才能让 progressDialog 持续到doInBackground() 线程完成?
【问题讨论】:
标签: android android-asynctask progressdialog