我正在从我的 android 应用程序向服务器发出请求,并且我正在使用 loopj 的 AsyncHttpClient 库来执行此操作。如果进度对话框被取消(按下后退键),我试图取消请求,但实际发生的是,ProgressDialog 被取消,但请求继续在后台工作,完成后将我带到另一个活动(这很好,因为这是我在未取消进度对话框时想要的行为)。
这是我的代码的一部分,我在其中设置了 ProgressDialog 的 setOnCancelListener:(客户端是 AsyncHttpClient 的一个实例)
public static void login(final String email, final String password,
final Context context, final Context appContext, final Resources res) {
prgDialog = new ProgressDialog(context);
prgDialog.setMessage(res.getString(R.string.dialog_please_wait));
prgDialog.setCancelable(true);
prgDialog.show();
prgDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
client.cancelRequests(context, true);
}
});
cookieStore = new PersistentCookieStore(appContext);
client.setCookieStore(cookieStore);
RequestParams params = new RequestParams();
params.put("user_session[email]", email);
params.put("user_session[password]", password);
client.addHeader("Accept", HEADER);
client.post(getAbsoluteUrl(LOGIN_PATH), params,
new JsonHttpResponseHandler() {
@Override
public void onFailure(int statusCode,
org.apache.http.Header[] headers,
java.lang.String responseString,
java.lang.Throwable throwable) {
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(context,
res.getString(R.string.error_404),
Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(context,
res.getString(R.string.error_500),
Toast.LENGTH_LONG).show();
} else if (statusCode == 401) {
Toast.makeText(context,
res.getString(R.string.login_401),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
context,
"Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
if (statusCode == 200) {
//do something
}
});
}