GDPR 同意书崩溃:WindowManager BadTokenException

GDPR Consent form crashing: WindowManager BadTokenException

我正在展示 Google's GDPR consent form,我注意到很多这样的报告:

Fatal Exception: android.view.WindowManager$BadTokenException
Unable to add window -- token android.os.BinderProxy@38734f2 is not valid; is your activity running?
com.my.project.MainActivity.onConsentFormLoaded

作为上下文,我使用 MainActivity.this:

private void displayConsentForm() {
    consentForm = new ConsentForm.Builder(MainActivity.this, GeneralUtils.getAppsPrivacyPolicy())
            .withListener(new ConsentFormListener() {
                @Override
                public void onConsentFormLoaded() {
                    consentForm.show(); // crashing here for some users
                }

                @Override
                public void onConsentFormOpened() { }

                @Override
                public void onConsentFormClosed(
                    ConsentStatus consentStatus, Boolean userPrefersAdFree) {

                    if(userPrefersAdFree) {
                            ConsentInformation.getInstance(MainActivity.this)
                                    .setConsentStatus(NON_PERSONALIZED);
                    } else {
                        ConsentInformation.getInstance(MainActivity.this)
                                .setConsentStatus(consentStatus);
                    }

                    initAds();
                }

                @Override
                public void onConsentFormError(String errorDescription) {
                    Log.e("Error",errorDescription);
                }
            })
            .withPersonalizedAdsOption()
            .withNonPersonalizedAdsOption()
            .withAdFreeOption()
            .build();

    consentForm.load();
}

这是额外的 Firebase 崩溃报告:

为什么会发生这种情况以及如何预防?我不确定在 consentForm.show() 之前要进行哪些额外检查,而且我无法重现该问题。如果我在显示表格之前进行此检查,也许就足够了:

if(!MainActivity.this.isFinishing() && !MainActivity.this.isDestroyed())

?

解决此问题的最简单方法是在 consentForm.show() 周围放置一个 try-catch 块并捕获 BadTokenException。

它不是很干净,但很可能在 Activity 完成时发生这种情况(可能用户在加载对话框时就从“最近”中关闭了应用程序)。

如果这是我的项目,我会首先尝试添加您拥有的 if 语句(尽管您不需要 MainActivity.this. 部分;您可以调用 isFinishing()isDestroyed()直接)。由于您引用的是 Activity 上下文,因此应该处理它。

但是,如果它仍然崩溃,您应该首先考虑重现它。尝试在调用 displayConsentForm() 之前转到,然后从“最近”中关闭该应用程序。调整一下时间,您可能会重现崩溃。如果没有,则只需添加 try-catch。 Activity 未显示,因为它抛出该错误,因此用户实际上不在应用程序中。