我的Android应用程序使用ProgressDialog
。当向服务器发送http请求(RESTFul Webservice)时,会显示对话框,当从服务器接收结果时隐藏对话框
private class GetMyTimeSheetTask extends AsyncTask<String, Void, String>
{
private ProgressDialog progress;
protected String doInBackground(String... params) {
MyTimeSheetFragment.this.getActivity().runOnUiThread(new Runnable() {
public void run() {
progress = new ProgressDialog(MyTimeSheetFragment.this.getContext());
progress.setTitle(getResources().getString(R.string.app_name));
progress.setMessage(getResources().getString(R.string.loading));
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(false);
progress.show();
}
} );
String result = HttpUtil.httpGet(
params[0], params[1],
params[2], params[3],
params[4]);
return result;
}
protected void onPostExecute(String param) {
progress.dismiss();
....
}
}
问题是有时服务器有问题,进度对话框永远显示,我不知道如何关闭它。如何解决这个问题呢?感谢您的帮助。
答案 0 :(得分:2)
您的HttpUtil应在发生错误时返回错误消息,并在超时时返回超时信息,以便您在收到这些异常消息时隐藏对话框。 我看不到HttpUtil代码,到目前为止可能是一个解决方案:
private class GetMyTimeSheetTask extends AsyncTask<String, Void, String> {
private static final int REQUEST_TIMEOUT = 5000;
private ProgressDialog progress;
private Handler handler = new Handler(Looper.getMainLooper());
private Runnable hideDialogTask = new Runnable(){
@Override
public void run() {
progress.dismiss();
}
};
protected String doInBackground(String... params) {
MyTimeSheetFragment.this.getActivity().runOnUiThread(new Runnable(){
public void run() {
progress = new ProgressDialog(MyTimeSheetFragment.this.getContext());
progress.setTitle(getResources().getString(R.string.app_name));
progress.setMessage(getResources().getString(R.string.loading));
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(false);
progress.show();
handler.postDelayed(hideDialogTask, REQUEST_TIMEOUT);
}
} );
String result = HttpUtil.httpGet(
params[0], params[1],
params[2], params[3],
params[4]);
return result;
}
protected void onPostExecute(String param) {
progress.dismiss();
....
}
}
答案 1 :(得分:1)
尝试实施超时方案以及异步任务