Android: “BadTokenException: Unable to add window; is your activity running?” at showing dialog in PreferenceActivity

前端 未结 6 1095
-上瘾入骨i
-上瘾入骨i 2021-01-30 16:06

I\'d like to ask for some help: In my app, I have only one activity, a PreferenceActivity (don\'t need other, it\'s just a simple background-sync app, so the

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 16:31

    After introducing crash tracking to a project, I noticed this issue popping up quite frequently and found the same fix worked throughout the project to eliminate the crash:

    • Never declare/instantiate Dialogs as local variables.
    • Make all Dialogs instance variables of the Activity.
    • Override onDestroy and call if(dialog != null) dialog.dismiss();

    Example:

    MyActivity extends Activity {
      ProgressDialog mProgressDialog;
      AlertDialog mAlertDialog;
    
    
      @Override
      public void onCreate(Bundle savedInstanceState) {
        mProgressDialog = new ProgressDialog(MyActivity.this);
        mAlertDialog = new AlertDialog.Builder(MyActivity.this).show();
      }
    
      @Override
      public void onDestroy() {
        super.onDestroy();
        if(mProgressDialog != null) {
          mProgressDialog.dismiss();
        }
        if(mAlertDialog != null) {
          mAlertDialog.dismiss();
        }
      }
    

    It is misleading that the error message says "unable to add window" as I've found the error happens when you are leaving an Activity and the context that was passed to your Dialog is dead.

提交回复
热议问题