按下后退按钮时AsyncTask终止任务

Arm*_*and 4 android android-asynctask

我在使用AsyncTask时遇到了一些问题.

我实现如下

 private class MakeConnection extends AsyncTask<String, Void, String> implements OnDismissListener{

    Context context;
    ProgressDialog myDialog;
    public MakeConnection(Context conetext)
    {
        this.context = conetext;
        myDialog = new ProgressDialog(this.context);
        myDialog.setCancelable(true);
        myDialog.setOnDismissListener(this);
    }

    @Override
    protected String doInBackground(String... urls) {
        //do stuff
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            myDialog.dismiss();
            success(result);
        }catch(JSONException e)
        {
            data = e.toString();
        }
    }

    @Override
      protected void onProgressUpdate(Void... values) {
            myDialog = ProgressDialog.show(context, "Please wait...", "Loading the data", true);
       }

    @Override
    public void onDismiss(DialogInterface dialog) {

        this.cancel(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我按下后退按钮时没有任何反应,它只是完成任务,好像我没有按下后退按钮

知道为什么吗?

ina*_*ruk 12

这个问题有两部分:

1)doInBackground()以这种方式实施,以便检查是否AsyncTask取消.

 @Override
 protected String doInBackground(String... urls) {
       for(int i = 0; i < 100 && !isCancelled(); i++) { 
          //do some stuff
      }
}
Run Code Online (Sandbox Code Playgroud)

2)你应该打电话给asynTask.cancel(true)你的活动onDestroy().