我正在从我的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
}
});
}
client.post(context,getAbsoluteUrl(LOGIN_PATH), params,
new JsonHttpResponseHandler();
在您的帖子中添加上下文参数。
尝试将方法更改为:
client.cancelAllRequests(true);
client.post(context, apiName, stringEntity, "text/plain",
uploadResponseHandler(callBack, apiNumber, requestId, context, resultClass)).setTag("uploadFile");
然后是>>
client.cancelRequestsByTAG("uploadFile",true);