我想在超时后取消AsyncTask
如果任务仍在运行,我想立即取消它。这是我的代码:
HttpURLConnection connection = null;
//GetRequestTask extends AsyncTask
final GetRequestsTask requestTask = new GetRequestsTask();
requestTask.execute(createUrl());
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("myapp", "entered handler");
if (requestTask.getStatus() == AsyncTask.Status.RUNNING) {
Log.d("myapp", "entered cancelling");
requestTask.cancel(true);
connection.disconnect();
}
}
}, TIME_OUT);
如您所见,我在HTTP
AsyncTask
方法中调用了doInBackground
个请求。当我想取消AsyncTask
时,我也会断开连接。
问题在于,当我拨打cancel(true)
并且我的应用日志entered cancelling
时,AsynkTask
不会立即取消,并会在至少10到20秒的延迟时间内取消。
我打电话取消后如何取消任务?
更新:这是我的`AsyncTask代码:
private class GetRequestsTask extends AsyncTask<URL, Void, JSONObject> {
@Override
protected void onPreExecute() {
Log.d("myapp", "entered onPreExecute");
mLoadingDialog.show();
}
@Override
protected JSONObject doInBackground(URL... urls) {
Log.d("myapp", "entered doInBackground");
try {
connection = (HttpURLConnection) urls[0].openConnection();
connection.setRequestProperty("Accept", "application/json");
int response = connection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
try {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
reader.close();
}
return new JSONObject(builder.toString());
}
else {
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
return null;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
Log.d("myapp", "entered onPostExecute");
mLoadingDialog.dismiss();
if (jsonObject == null) {
showNoInternetDialog();
}
else {
convertJSONtoArrayList(jsonObject);
mRequestArrayAdapter.notifyDataSetChanged();
mListView.smoothScrollToPosition(0);
}
}
@Override
protected void onCancelled() {
Log.d("myapp", "entered onCancelled");
mLoadingDialog.dismiss();
showNoInternetDialog();
}
问题是我的超时是20秒,但在35,40秒后调用onCancelled
。
答案 0 :(得分:0)
如果您正在进行计算:
如果您正在执行HTTP请求:
另外如果您使用某个库来提供方便的请求,那么我认为它应该有一些 cancel()方法。例如,对于retrofit there is such method.
因此,在这种情况下,如果你正在做一个HTTP请求&#39;部分。你需要:
还有一个替代方案是rxJava。借助此库,您可以为您的请求创建Observable并保存对其订阅的引用。然后你只需要调用savedSubscription.unsubscribe()就可以了。
另外,请不要将异步任务用作内部类。