134

一些用户正在报告,如果他们使用通知栏中的快速操作,他们就会强制关闭。

我在调用“TestDialog”类的通知中显示了一个快速操作。在按下按钮“贪睡”后的 TestDialog 类中,我将显示贪睡对话框。

private View.OnClickListener btnSnoozeOnClick() {
    return new View.OnClickListener() {

        public void onClick(View v) {
            showSnoozeDialog();
        }
    };
}

private void showSnoozeDialog() {
    FragmentManager fm = getSupportFragmentManager();
    SnoozeDialog snoozeDialog = new SnoozeDialog();
    snoozeDialog.show(fm, "snooze_dialog");
}

错误是*IllegalStateException: Can not perform this action after onSaveInstanceState*.

IllegarStateException 被触发的代码行是:

snoozeDialog.show(fm, "snooze_dialog");

该类正在扩展“FragmentActivity”,而“SnoozeDialog”类正在扩展“DialogFragment”。

这是错误的完整堆栈跟踪:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1327)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1338)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:127)
at com.test.testing.TestDialog.f(TestDialog.java:538)
at com.test.testing.TestDialog.e(TestDialog.java:524)
at com.test.testing.TestDialog.d(TestDialog.java:519)
at com.test.testing.g.onClick(TestDialog.java:648)
at android.view.View.performClick(View.java:3620)
at android.view.View$PerformClick.run(View.java:14292)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)

我无法重现此错误,但我收到了很多错误报告。

任何人都可以帮助我如何解决这个错误?

4

17 回答 17

73

这是常见的问题。我们通过覆盖 show() 并在 DialogFragment 扩展类中处理异常解决了这个问题

public class CustomDialogFragment extends DialogFragment {

    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commit();
        } catch (IllegalStateException e) {
            Log.d("ABSDIALOGFRAG", "Exception", e);
        }
    }
}

请注意,应用此方法不会改变 DialogFragment.class 的内部字段:

boolean mDismissed;
boolean mShownByMe;

在某些情况下,这可能会导致意外结果。更好地使用 commitAllowingStateLoss() 而不是 commit()

于 2016-02-16T11:22:00.417 回答
29

这意味着您commit()show()在 DialogFragment 的情况下)在onSaveInstanceState().

Android 会将您的片段状态保存在onSaveInstanceState(). 因此,如果您在片段状态commit()之后进行片段,onSaveInstanceState()则会丢失。

结果,如果 Activity 被杀死并稍后重新创建,片段将不会添加到糟糕的用户体验的活动中。这就是为什么 Android 不允许不惜一切代价进行状态丢失。

简单的解决方案是检查状态是否已经保存。

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");
    }
}

注意:onResumeFragments() 将在片段恢复时调用。

于 2014-09-07T01:20:34.330 回答
24

使用 Activity-KTX 的新生命周期范围就像以下代码示例一样简单:

lifecycleScope.launchWhenResumed {
   showErrorDialog(...)
}

该方法可以在 onStop() 之后直接调用,并且在返回时调用 onResume() 将成功显示对话框。

于 2020-02-04T00:32:39.323 回答
21
private void showSnoozeDialog() {
    FragmentManager fm = getSupportFragmentManager();
    SnoozeDialog snoozeDialog = new SnoozeDialog();
    // snoozeDialog.show(fm, "snooze_dialog");
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(snoozeDialog, "snooze_dialog");
    ft.commitAllowingStateLoss();
}

参考:链接

于 2016-10-20T18:25:30.620 回答
16

几天后,我想分享我的解决方案如何修复它,以显示 DialogFragment 你应该覆盖show()它的方法并调用commitAllowingStateLoss()对象Transaction。这是 Kotlin 中的示例:

override fun show(manager: FragmentManager?, tag: String?) {
        try {
            val ft = manager?.beginTransaction()
            ft?.add(this, tag)
            ft?.commitAllowingStateLoss()
        } catch (ignored: IllegalStateException) {

        }

    }
于 2017-01-23T19:17:42.163 回答
12

如果对话框不是很重要(可以在应用关闭/不再显示时不显示它),请使用:

boolean running = false;

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

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

并且仅在我们运行时打开您的对话框(片段):

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

编辑,可能更好的解决方案:

在生命周期中调用 onSaveInstanceState 的位置是不可预测的,我认为更好的解决方案是像这样检查 isSavedInstanceStateDone() :

/**
 * 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;
}
于 2014-06-19T10:23:09.957 回答
11

我多年来一直遇到这个问题。
互联网上充斥着数十次(数十万次?数千次?)关于此的讨论,其中似乎充斥着混乱和虚假信息。
更糟糕的是,本着 xkcd“14 标准”漫画的精神,我将我的答案扔给了戒指。
xkcd 14 标准

, , 和类似的cancelPendingInputEvents()解决commitAllowingStateLoss()方案catch (IllegalStateException e)看起来都很糟糕。

希望以下内容可以轻松地展示如何重现和解决问题:

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);
    }
};
于 2018-03-15T20:52:49.240 回答
6

请尝试使用 FragmentTransaction 而不是 FragmentManager。我认为下面的代码将解决您的问题。如果没有,请告诉我。

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SnoozeDialog snoozeDialog = new SnoozeDialog();
snoozeDialog.show(ft, "snooze_dialog");

编辑:

分片交易

请检查此链接。我认为它将解决您的疑问。

于 2013-12-26T11:42:26.170 回答
5

使您的对话框片段对象全局并在 onPause() 方法中调用dismissAllowingStateLoss()

@Override
protected void onPause() {
    super.onPause();

    if (dialogFragment != null) {
        dialogFragment.dismissAllowingStateLoss();
    }
}

不要忘记在片段中分配值并在按钮单击或任何地方调用 show() 。

于 2018-10-16T13:44:41.403 回答
3

许多视图将高级事件(例如单击处理程序)发布到事件队列以延迟运行。所以问题是已经为活动调用了“onSaveInstanceState”,但事件队列包含延迟的“点击事件”。因此,当此事件被分派给您的处理程序时

at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)

并且您的代码确实show抛出了 IllegalStateException。

最简单的解决方案是清理事件队列,在onSaveInstanceState

protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // ..... do some work
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            findViewById(android.R.id.content).cancelPendingInputEvents();
        }
}
于 2017-11-30T14:02:58.397 回答
3

使用此代码

FragmentTransaction ft = fm.beginTransaction();
        ft.add(yourFragment, "fragment_tag");
        ft.commitAllowingStateLoss();

代替

yourFragment.show(fm, "fragment_tag");
于 2019-08-24T21:35:42.493 回答
2

如果您覆盖 show() 函数,请不要这样做:

override fun show(manager: FragmentManager, tag: String?) {
    // mDismissed = false; is removed -> lead to wrong state
    // mShownByMe = true; is removed -> lead to wrong state
    val ft = manager.beginTransaction()
    ft.add(this, tag)
    ft.commitAllowingStateLoss()
}

它可能导致错误的对话状态

做就是了:

override fun show(manager: FragmentManager, tag: String?) {
    try {
        super.show(manager, tag)
    } catch (e: Exception) {
        val ft = manager.beginTransaction()
        ft.add(this, tag)
        ft.commitAllowingStateLoss()
    }
}
于 2020-10-22T08:57:21.210 回答
2

通过使用反射,我找到了一个优雅的解决方案。以上所有解决方案的问题是字段mDismissedmShownByMe不会改变它们的状态。

只需在您自己的自定义底部工作表对话框片段中覆盖方法“显示”,如下面的示例(Kotlin)

override fun show(manager: FragmentManager, tag: String?) {
        val mDismissedField = DialogFragment::class.java.getDeclaredField("mDismissed")
        mDismissedField.isAccessible = true
        mDismissedField.setBoolean(this, false)

        val mShownByMeField = DialogFragment::class.java.getDeclaredField("mShownByMe")
        mShownByMeField.isAccessible = true
        mShownByMeField.setBoolean(this, true)

        manager.beginTransaction()
                .add(this, tag)
                .commitAllowingStateLoss()
    }
于 2019-11-27T17:06:55.810 回答
1

虽然它没有在任何地方正式提及,但我几次遇到这个问题。根据我的经验,在旧平台上支持片段的兼容性库存在问题,这会导致此问题。您可以使用普通的片段管理器 API 对此进行测试。如果没有任何效果,那么您可以使用普通对话框而不是对话框片段。

于 2013-12-24T19:09:16.650 回答
1
  1. 将此类添加到您的项目中:(必须在android.support.v4.app包中)
包android.support.v4.app;


/**
 * 由 Gil 于 2017 年 8 月 16 日创建。
 */

公共类 StatelessDialogFragment 扩展 DialogFragment {
    /**
     * 显示对话框,使用现有事务添加片段,然后提交
     * 交易同时允许状态丢失。
* * 我建议你大部分时间使用 {@link #show(FragmentTransaction, String)} 但是 * 这适用于您真的不关心的对话。(调试/跟踪/广告等) * * @param 交易 * 在其中添加片段的现有事务。 * @param 标记 * 此片段的标签,根据 * {@link FragmentTransaction#add(Fragment, String) FragmentTransaction.add}。 * @return 返回已提交事务的标识符,按照 * {@link FragmentTransaction#commit() FragmentTransaction.commit()}。 * @see StatelessDialogFragment#showAllowingStateLoss(FragmentManager, String) */ public int showAllowingStateLoss(FragmentTransaction 交易,字符串标签) { mDismissed = 假; mShownByMe = 真; transaction.add(this, tag); mViewDestroyed = 假; mBackStackId = transaction.commitAllowingStateLoss(); 返回 mBackStackId; } /** * 显示对话框,将片段添加到给定的 FragmentManager。这是一个方便 * 用于显式创建事务,使用给定标签将片段添加到其中,以及 * 在不关心状态的情况下提交它。这不会交易添加到 * 回栈。当片段被解除时,将执行一个新的事务来移除它 * 来自活动。
* * 我建议你大部分时间使用 {@link #show(FragmentManager, String)} 但这是 * 对于你真的不关心的对话。(调试/跟踪/广告等) * * * @参数管理器 * 这个片段将被添加到的 FragmentManager。 * @param 标记 * 此片段的标签,根据 * {@link FragmentTransaction#add(Fragment, String) FragmentTransaction.add}。 * @see StatelessDialogFragment#showAllowingStateLoss(FragmentTransaction, String) */ public void showAllowingStateLoss(FragmentManager 管理器,字符串标签) { mDismissed = 假; mShownByMe = 真; FragmentTransaction ft = manager.beginTransaction(); ft.add(这个,标签); ft.commitAllowingStateLoss(); } }
  1. 扩展StatelessDialogFragment而不是 DialogFragment
  2. 使用方法showAllowingStateLoss而不是 show

  3. 享受 ;)

于 2017-08-16T09:38:42.970 回答
0

此错误似乎正在发生,因为输入事件(例如按键或点击事件)在onSaveInstanceState被调用后被传递。

解决方案是在您的活动中覆盖onSaveInstanceState并取消任何未决事件。

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final View rootView = findViewById(android.R.id.content);
        if (rootView != null) {
            rootView.cancelPendingInputEvents();
        }
    }
}
于 2018-02-09T02:42:28.547 回答
0

以下实现可用于解决在Activity生命周期中安全地执行状态更改的问题,特别是用于显示对话框:如果实例状态已经保存(例如由于配置更改),它将推迟它们直到恢复状态被执行。

public abstract class XAppCompatActivity extends AppCompatActivity {

    private String TAG = this.getClass().getSimpleName();

    /** The retained fragment for this activity */
    private ActivityRetainFragment retainFragment;

    /** If true the instance state has been saved and we are going to die... */
    private boolean instanceStateSaved;

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // get hold of retain Fragment we'll be using
        retainFragment = ActivityRetainFragment.get(this, "Fragment-" + this.getClass().getName());
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

        // reset instance saved state
        instanceStateSaved = false;

        // execute all the posted tasks
        for (ActivityTask task : retainFragment.tasks) task.exec(this);
        retainFragment.tasks.clear();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        instanceStateSaved = true;
    }

    /**
     * Checks if the activity state has been already saved.
     * After that event we are no longer allowed to commit fragment transactions.
     * @return true if the instance state has been saved
     */
    public boolean isInstanceStateSaved() {
        return instanceStateSaved;
    }

    /**
     * Posts a task to be executed when the activity state has not yet been saved
     * @param task The task to be executed
     * @return true if the task executed immediately, false if it has been queued
     */
    public final boolean post(ActivityTask task)
    {
        // execute it immediately if we have not been saved
        if (!isInstanceStateSaved()) {
            task.exec(this);
            return true;
        }

        // save it for better times
        retainFragment.tasks.add(task);
        return false;
    }

    /** Fragment used to retain activity data among re-instantiations */
    public static class ActivityRetainFragment extends Fragment {

        /**
         * Returns the single instance of this fragment, creating it if necessary
         * @param activity The Activity performing the request
         * @param name The name to be given to the Fragment
         * @return The Fragment
         */
        public static ActivityRetainFragment get(XAppCompatActivity activity, String name) {

            // find the retained fragment on activity restarts
            FragmentManager fm = activity.getSupportFragmentManager();
            ActivityRetainFragment fragment = (ActivityRetainFragment) fm.findFragmentByTag(name);

            // create the fragment and data the first time
            if (fragment == null) {
                // add the fragment
                fragment = new ActivityRetainFragment();
                fm.beginTransaction().add(fragment, name).commit();
            }

            return fragment;
        }

        /** The queued tasks */
        private LinkedList<ActivityTask> tasks = new LinkedList<>();

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);

            // retain this fragment
            setRetainInstance(true);
        }

    }

    /** A task which needs to be performed by the activity when it is "fully operational" */
    public interface ActivityTask {

        /**
         * Executed this task on the specified activity
         * @param activity The activity
         */
        void exec(XAppCompatActivity activity);
    }
}

然后使用这样的类:

/** AppCompatDialogFragment implementing additional compatibility checks */
public abstract class XAppCompatDialogFragment extends AppCompatDialogFragment {

    /**
     * Shows this dialog as soon as possible
     * @param activity The activity to which this dialog belongs to
     * @param tag The dialog fragment tag
     * @return true if the dialog has been shown immediately, false if the activity state has been saved
     *         and it is not possible to show it immediately
     */
    public boolean showRequest(XAppCompatActivity activity, final String tag) {
        return showRequest(activity, tag, null);
    }

    /**
     * Shows this dialog as soon as possible
     * @param activity The activity to which this dialog belongs to
     * @param tag The dialog fragment tag
     * @param args The dialog arguments
     * @return true if the dialog has been shown immediately, false if the activity state has been saved
     *         and it is not possible to show it immediately
     */
    public boolean showRequest(XAppCompatActivity activity, final String tag, final Bundle args)
    {
        return activity.post(new XAppCompatActivity.ActivityTask() {
            @Override
            public void exec(XAppCompatActivity activity) {
                if (args!= null) setArguments(args);
                show(activity.getSupportFragmentManager(), tag);
            }
        });
    }

    /**
     * Dismiss this dialog as soon as possible
     * @return true if the dialog has been dismissed immediately, false if the activity state has been saved
     *         and it is not possible to dismissed it immediately
     */
    public boolean dismissRequest()
    {
        return dismissRequest(null);
    }

    /**
     * Dismiss this dialog as soon as possible
     * @param runnable Actions to be performed before dialog dismissal
     * @return true if the dialog has been dismissed immediately, false if the activity state has been saved
     *         and it is not possible to dismissed it immediately
     */
    public boolean dismissRequest(final Runnable runnable)
    {
        // workaround as in rare cases the activity could be null
        XAppCompatActivity activity = (XAppCompatActivity)getActivity();
        if (activity == null) return false;

        // post the dialog dismissal
        return activity.post(new XAppCompatActivity.ActivityTask() {
            @Override
            public void exec(XAppCompatActivity activity) {
                if (runnable != null) runnable.run();
                dismiss();
            }
        });
    }
}

您可以安全地显示对话框而不必担心应用程序状态:

public class TestDialog extends XAppCompatDialogFragment {

    private final static String TEST_DIALOG = "TEST_DIALOG";

    public static void show(XAppCompatActivity activity) {
        new TestDialog().showRequest(activity, TEST_DIALOG);
    }

    public TestDialog() {}

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        return new AlertDialog.Builder(getActivity(), R.style.DialogFragmentTheme /* or null as you prefer */)
                .setTitle(R.string.title)
                // set all the other parameters you need, e.g. Message, Icon, etc.
                ).create();
    }
}

然后TestDialog.show(this)从您的XAppCompatActivity.

如果您想创建一个更通用的带参数对话框类,您可以将它们Bundle与方法中的参数一起保存在 a 中,并使用inshow()检索它们。getArguments()onCreateDialog()

整个方法可能看起来有点复杂,但是一旦为活动和对话框创建了两个基类,它就非常易于使用并且可以完美运行。它可用于Fragment可能受相同问题影响的其他基于操作。

于 2017-03-20T17:17:32.877 回答