如何取消AsyncTask

时间:2014-09-04 06:09:44

标签: java android android-asynctask

我试图在用户按下或关闭Dialog时取消我的请求。但即使我取消它也至少执行一次。 sendPost用于上传图片。我想当用户取消Dialog时请求不应执行

private class sendd extends AsyncTask<Void, Void, Void> {
    String success, mess, response, user;
    Button next;
    ProgressDialog pDialog;

    public sendd(Context ctx) {
        pDialog = new ProgressDialog(FilenewReport.this);
        pDialog.setMessage("Updating ");
        pDialog.setCancelable(true);
        pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // actually could set running = false; right here, but I'll
                // stick to contract.
                running = false;
                // cancel(true);
                sends.cancel(true);
            }
        });

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog.show();
    }

    @Override
    protected void onCancelled() {
        sends.cancel(true);
        running = false;

    }

    @SuppressLint("NewApi")
    @Override
    protected Void doInBackground(Void... params) {
        while (running) {

            try {
                sendPost(file_url, imagepath);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                // }
            }
            // if (check == false || isCancelled()) {
            // break;
            // }
        }
        return null;

    }

    @Override
    protected void onPostExecute(Void notUsed) {

        pDialog.dismiss();

    }

}

2 个答案:

答案 0 :(得分:0)

添加到doInBackground中while循环的开头:

if (isCancelled()) {
    return null;
}

onPostExecute在此之后不会被执行,只有onCancelled

答案 1 :(得分:0)

使用它来取消doInBackground中的请求:

    httpclient.getConnectionManager().shutdown();
在这种情况下,

onPostExecute方法不会执行。