On showing dialog i get “Can not perform this action after onSaveInstanceState”

前端 未结 17 1091
甜味超标
甜味超标 2020-11-29 18:37

Some users are reporting, if they use the quick action in the notification bar, they are getting a force close.

I show a quick action in the notification who calls t

17条回答
  •  旧时难觅i
    2020-11-29 19:15

    That mean you commit() (show() in case of DialogFragment) fragment after onSaveInstanceState().

    Android will save your fragment state at onSaveInstanceState(). So, if you commit() fragment after onSaveInstanceState() fragment state will be lost.

    As a result, if Activity get killed and recreate later the fragment will not add to activity which is bad user experience. That's why Android does not allow state loss at all costs.

    The easy solution is to check whether state already saved.

    boolean mIsStateAlreadySaved = false;
    boolean mPendingShowDialog = false;
    
    @Override
    public void onResumeFragments(){
        super.onResumeFragments();
        mIsStateAlreadySaved = false;
        if(mPendingShowDialog){
            mPendingShowDialog = false;
            showSnoozeDialog();
        }
    }
    
    @Override
    public void onPause() {
        super.onPause();
        mIsStateAlreadySaved = true;
    }
    
    private void showSnoozeDialog() {
        if(mIsStateAlreadySaved){
            mPendingShowDialog = true;
        }else{
            FragmentManager fm = getSupportFragmentManager();
            SnoozeDialog snoozeDialog = new SnoozeDialog();
            snoozeDialog.show(fm, "snooze_dialog");
        }
    }
    

    Note: onResumeFragments() will call when fragments resumed.

提交回复
热议问题