Android Back Button and Progress Dialog

前端 未结 9 2048
攒了一身酷
攒了一身酷 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: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.

提交回复
热议问题