AsyncTask kill task when back button pressed

随声附和 提交于 2020-01-03 17:02:49

问题


I am having a little problems with AsyncTask.

I have it implemented as follows

 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);
    }
}

But when ever I press the back button nothing happens, it just completes the task as if I didn't press the back button

Any idea why?


回答1:


There are two parts of this problem:

1) Implement your doInBackground() in such a way, so it checks whether AsyncTask is cancelled.

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

2) You should call asynTask.cancel(true) in your Activity's onDestroy().




回答2:


This fixes my problem

@Override
protected void onPreExecute(){
    myDialog = ProgressDialog.show(
            context,
            "Please wait...",
            "Loading the data",
            true,
            true,
            new DialogInterface.OnCancelListener(){
                @Override
                public void onCancel(DialogInterface dialog) {
                    MakeConnection.this.cancel(true);
                }
            }
    );
}



回答3:


it is also possible to use follwing method in activity

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    imageLoadingAsyncTask.cancel(true);
}


来源:https://stackoverflow.com/questions/7095958/asynctask-kill-task-when-back-button-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!