Android - Stop AsyncTask when back button is pressed and return to previous Activity

╄→гoц情女王★ 提交于 2020-01-12 05:31:08

问题


I've an AsyncTask and I want it to stip execution when back button is pressed. I also want the app to return to the previous displayed Activity. It seems I've managed in stop the Task but the app doesn't return to the previous activity. Any ideas? This is an extract from my code

private class MyTask extends AsyncTask<Void, Void, Void> implements OnDismissListener{
    private boolean exception= false;

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

    @Override
    protected Void doInBackground(Void... voids) {
        //do something
        return (null);
    }

    @Override
    protected void onPostExecute(Void voids) {
        pd.dismiss();
        //do something

    }

    public void onDismiss(DialogInterface dialog) {

        this.cancel(true);
    }

}

Regards.


回答1:


pd.setCancelable(true);
    pd.setOnCancelListener(cancelListener);
    bCancelled=false;

 pd is your progressdialog box

and now use cancelListner

    OnCancelListener cancelListener=new OnCancelListener(){
    @Override
    public void onCancel(DialogInterface arg0){
        bCancelled=true;
        finish();
    }
};



回答2:


In your activity, override Back Button, stop the AsyncTask in it, and call finish for current activity.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
         MyTask.cancel();
      IscrizioniActivity.this.finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}



回答3:


Have you tried adding a finish() call in the onDismiss() method:

public void onDismiss(DialogInterface dialog) {
    this.cancel(true);
    IscrizioniActivity.this.finish();
}



回答4:


Try this one...

progress_dialog.setCancelable(true);
progress_dialog.setOnCancelListener(new OnCancelListener() {

    @Override
    public void onCancel(DialogInterface dialog) {
        // TODO Auto-generated method stub
        YourActivity.this.finish();
        }
    });


来源:https://stackoverflow.com/questions/8209035/android-stop-asynctask-when-back-button-is-pressed-and-return-to-previous-acti

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