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

前端 未结 17 1069
甜味超标
甜味超标 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:18

    I have run in to this problem for years.
    The Internets are littered with scores (hundreds? thousands?) of discussions about this, and confusion and disinformation in them seems aplenty.
    To make the situation worse, and in the spirit of the xkcd "14 standards" comic, I am throwing in my answer in to the ring.

    The cancelPendingInputEvents(), commitAllowingStateLoss(), catch (IllegalStateException e), and similar solutions all seem atrocious.

    Hopefully the following easily shows how to reproduce and fix the problem:

    private static final Handler sHandler = new Handler();
    private boolean mIsAfterOnSaveInstanceState = true;
    
    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        mIsAfterOnSaveInstanceState = true; // <- To repro, comment out this line
    }
    
    @Override
    protected void onPostResume()
    {
        super.onPostResume();
        mIsAfterOnSaveInstanceState = false;
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        sHandler.removeCallbacks(test);
    }
    
    @Override
    protected void onPause()
    {
        super.onPause();
        sHandler.postDelayed(test, 5000);
    }
    
    Runnable test = new Runnable()
    {
        @Override
        public void run()
        {
            if (mIsAfterOnSaveInstanceState)
            {
                // TODO: Consider saving state so that during or after onPostResume a dialog can be shown with the latest text
                return;
            }
    
            FragmentManager fm = getSupportFragmentManager();
            DialogFragment dialogFragment = (DialogFragment) fm.findFragmentByTag("foo");
            if (dialogFragment != null)
            {
                dialogFragment.dismiss();
            }
    
            dialogFragment = GenericPromptSingleButtonDialogFragment.newInstance("title", "message", "button");
            dialogFragment.show(fm, "foo");
    
            sHandler.postDelayed(test, 5000);
        }
    };
    

提交回复
热议问题