Android Back Button and Progress Dialog

前端 未结 9 2241
攒了一身酷
攒了一身酷 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: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();
       }
    }
    

提交回复
热议问题