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

前端 未结 4 1930
再見小時候
再見小時候 2021-02-09 04:22

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

相关标签:
4条回答
  • 2021-02-09 05:02

    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);
    }
    
    0 讨论(0)
  • 2021-02-09 05:11

    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();
            }
        });
    
    0 讨论(0)
  • 2021-02-09 05:14
    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();
        }
    };
    
    0 讨论(0)
  • 2021-02-09 05:17

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

    public void onDismiss(DialogInterface dialog) {
        this.cancel(true);
        IscrizioniActivity.this.finish();
    }
    
    0 讨论(0)
提交回复
热议问题