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

前端 未结 17 1062
甜味超标
甜味超标 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条回答
  •  独厮守ぢ
    2020-11-29 19:29

    If the dialog is not really important (it is okay to not-show it when the app closed/is no longer in view), use:

    boolean running = false;
    
    @Override
    public void onStart() {
        running = true;
        super.onStart();
    }
    
    @Override
    public void onStop() {
        running = false;
        super.onStop();
    }
    

    And open your dialog(fragment) only when we're running:

    if (running) {
        yourDialog.show(...);
    }
    

    EDIT, PROBABLY BETTER SOLUTION:

    Where onSaveInstanceState is called in the lifecycle is unpredictable, I think a better solution is to check on isSavedInstanceStateDone() like this:

    /**
     * True if SavedInstanceState was done, and activity was not restarted or resumed yet.
     */
    private boolean savedInstanceStateDone;
    
    @Override
    protected void onResume() {
        super.onResume();
    
        savedInstanceStateDone = false;
    }
    
    @Override
    protected void onStart() {
        super.onStart();
    
        savedInstanceStateDone = false;
    }
    
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        savedInstanceStateDone = true;
    }
    
    
    /**
     * Returns true if SavedInstanceState was done, and activity was not restarted or resumed yet.
     */
    public boolean isSavedInstanceStateDone() {
        return savedInstanceStateDone;
    }
    

提交回复
热议问题