撤销权限后出现 IllegalStateException

IllegalStateException after revoking permissions

用户在设置中撤销权限并从后台返回后,我的应用程序崩溃并出现 IllegalStateException:OnSaveInstanceState 后无法执行此操作。我看到 OS 试图从后台重新创建片段堆栈(重新启动应用程序不会导致崩溃)。我已经尝试使用标志捕获撤销操作,如果为真,则只向用户显示一个对话框,通知用户重新启动应用程序。但是在显示对话框后,OS 仍然继续尝试重新创建堆栈,因此崩溃。

如果标志为真,我也尝试弹出所有片段,但没有成功。

Google 开发人员已声明撤销权限将导致应用程序失去功能,但崩溃不仅仅是失去功能。如何在显示对话框后暂停应用程序?

撤销权限会杀死您未销毁的活动,当您 return 时,它们可能会通过 savedInstanceState 恢复,而不是您测试的通常方式。

您发布的异常意味着您的代码在 onSaveInstanceState()(或 onPause()onStop(),通常在之后调用),或者作为某些异步操作的结果,您在 Activity 最小化时忘记取消。

为了安全起见,我通常会跟踪我是否可以提交 FragmentTransactions,就像这样

public abstract class BaseActivity extends AppCompatActivity {

    private boolean mFragmentTransactionsAllowed;

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentTransactionsAllowed = true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        mFragmentTransactionsAllowed = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFragmentTransactionsAllowed = true;
    }

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        mFragmentTransactionsAllowed = false;
    }

    protected final boolean areFragmentTransactionsAllowed() {
        return mFragmentTransactionsAllowed;
    }
}

在提交之前我会检查

if (areFragmentTransactionsAllowed()) {
    ft.commit();
}