Android Back Button and Progress Dialog

前端 未结 9 2044
攒了一身酷
攒了一身酷 2021-01-31 03:24

I have an AsyncTask that shows a progressDialog whilst working (it calls runOnUiThread from within doInBackground to show the progress dialog).

<
相关标签:
9条回答
  • 2021-01-31 03:39

    First, you should show your dialog from OnPreExecute, hide it in OnPostExecute, and - if necessary - modify it by publishing progress. (see here)

    Now to your question: ProgressDialog.show() can take a OnCancelListener as an argument. You should provide one that calls cancel() on the progress dialog instance.

    example:

        @Override
        protected void onPreExecute(){
            _progressDialog = ProgressDialog.show(
                    YourActivity.this,
                    "Title",
                    "Message",
                    true,
                    true,
                    new DialogInterface.OnCancelListener(){
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            YourTask.this.cancel(true);
                            finish();
                        }
                    }
            );
        }
    

    where _progressDialog is a ProgressDialog member of YourTask.

    This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. LINK

    0 讨论(0)
  • 2021-01-31 03:45

    Here's my solution to this. The PD problem occurs only when the app exiting on back button (Usually when the user presses it repetitively, and only sometimes (not all the times) the PD is called when the app already destroyed. Dismissing the PD onDestroy doesn't work for some reason and when I've tried it, each Back button press would close the app although canGoBack() was set to true. Instead I dismiss the PD on goBack which is the event that causes the collision in the first place, and I do it right before finish(). If the app exits on goBack normally there's no problem in the first place.

    BTW, 'difference' is aimed to let the user to exit the app with a fast double click (400 MS between two clicks) instead of going back from page to page.

    Hope it helps someone...

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                difference = System.currentTimeMillis() - startTime;
                if (wView.canGoBack() && difference > 400) {
                    wView.goBack();
                } else {
                    dismissProgressDialog();
                    finish();
                }
                startTime = System.currentTimeMillis();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    
    
    private void dismissProgressDialog() {
       if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
       }
    }
    
    0 讨论(0)
  • 2021-01-31 03:51

    I just found a perfect and simplest solution to this problem. There's a method in ProgressDialog to set KeyListener.

    progressDialog.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if(keyCode==KeyEvent.KEYCODE_BACK && !event.isCanceled()) {
                if(progressDialog.isShowing()) {
                    //your logic here for back button pressed event
                } 
                return true;
            }
            return false;
        }
    });
    

    It's working fine with setCancelable(false). I am also checking for event.isCanceled(), because without that I was getting two events. I've tested this on Lollipop device with and without Hardware keys.

    0 讨论(0)
  • 2021-01-31 03:52

    javano... I tested your scenario using standard techniques, asyncTask and ProgressDialog. In my test, when the progressDialog is showing and i hit back, the progressdialog is dismissed and the background thread continues to run. I do not know why you need to call runOnUiThread.

    SO:

    show the progressDialog in onPreExecute place the long running task in doInBackground dismiss the progressDialog in onPostExecute pass the input parameters to your long running task as in:

    new MyAsynch().execute(password,inString);
    

    cancel() the asynchTask and progressDialog in onPause

    protected void onPause() {
        super.onPause();
        if (asynch != null) {asynch.cancel(true);}
        if (progress != null){progress.cancel();}
    }
    

    JAL

    I have some code here.

    0 讨论(0)
  • 2021-01-31 03:53

    Treating back button like a cancellation is not the correct way.
    Cancellation also occurs when a user touches the screen outside of the dialog box. You want to differentiate those two actions, no?

    Correct approach would be to extend the ProgressDialog class and override the onBackPressed method.

    private class SubProgressDialog extends ProgressDialog {
        public SubProgressDialog(Context context) {
            super(context);
        }
        @Override
        public void onBackPressed() {
            /** dismiss the progress bar and clean up here **/
        }
    }
    
    
    public void displayProgressBar(){
        progressBar = new SubProgressDialog(this);
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressBar.setCancelable(false);
        progressBar.setMessage(getString(R.string.authorizing));        
        progressBar.show();   
        new Thread(new Runnable() {
          public void run() {
          }
           }).start();     
    

    }

    Notice the setCancelable(false), again emphasizing that back button is different than a simple cancellation.
    Also this will effecitvely ignore any other touch inputs from the user.

    0 讨论(0)
  • 2021-01-31 03:55

    This can be achieved by the following code fragment:

    progress.setCancelable(true);
    progress.setCanceledOnTouchOutside(false);
    

    progress is the ProgressDialog object...

    This will enable the back button to close the dialog but prevent any touch input to do that...

    0 讨论(0)
提交回复
热议问题