AlertDialog show() 给出 WindowManager BadTokenException

AlertDialog show() giving WindowManager BadTokenException

我在 Google Play 开发者控制台上收到了很多关于该异常的报告,我不明白为什么,因为我无法重现错误,它在我所有的设备上都能完美运行.

这是我的自定义 AlertDialog 的源代码,崩溃行在方法末尾的 show() 调用上。怎么了?

我在 Stack Overflow 上查了一些相关的问题,但我实际上在声明对话框时使用 final,这是其他问题的解决方案,我仍然有异常报告。

public static void showPoliciesDialog(final Activity activity, final Runnable runnable) {
    int sw = App.getInstance().getSmallSideSize();
    final int LIGHT_GRAY = 0xFFc7c7c7;

    final AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.PolicyStyle));
    builder.setCancelable(false);

    LinearLayout ll = new LinearLayout(activity);
    ll.setPadding((int)(sw*0.025), 0, (int)(sw*0.025), 0);
    ll.setOrientation(LinearLayout.VERTICAL);

    final TextView title = new TextView(activity);
    LinearLayout.LayoutParams titleLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT );
    titleLP.setMargins( Util.dpToPx(activity, 15), Util.dpToPx(activity, 15), Util.dpToPx(activity, 15), Util.dpToPx(activity, 15) );
    title.setLayoutParams(titleLP );
    title.setTextSize(18);
    title.setText(R.string.POLICY_TITLE);
    title.setTextColor(0xFF307282); // Blue color
    ll.addView(title);

    final CheckBox acceptCheckbox = new CheckBox(activity);
    acceptCheckbox.setTextColor(LIGHT_GRAY);
    acceptCheckbox.setText(R.string.I_WANT_DATA_COLLECT);
    acceptCheckbox.setLayoutParams( new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) );
    acceptCheckbox.setVisibility(View.GONE);
    acceptCheckbox.setChecked(App.getInstance().retrieveBooleanValue(Constants.SEND_DATA_CHECKBOX, ConfigManager.getInstance().defaultStorable()));
    acceptCheckbox.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                App.getInstance().storeBooleanValue(Constants.SEND_DATA_CHECKBOX, isChecked);
            }
        }
    );
    acceptCheckbox.setPadding(5,5,5,5);

    // Detects if the end of the web page has been reached & in this case it shows the accept checkbox.
    // Based on 
    // And on
    // [1] - 
    // [2] - (To avoid use of an deprecated method) 
    final WebView policiesWebView = new WebView(activity){
        float currentScale = -1;
        {
            this.setWebViewClient(new WebViewClient(){
                @Override public void onScaleChanged(WebView view, float oldScale, float newScale) {
                    super.onScaleChanged(view, oldScale, newScale);
                    currentScale = newScale;
                }
            });
            this.getSettings().setJavaScriptEnabled(true);
        }
        @Override public void onScrollChanged(int l, int t, int oldl, int oldt) {
            // Only called on Android versions where onScaleChanged is not called
            if(currentScale == -1)
                currentScale = this.getScale();
            int height = (int) Math.floor(this.getContentHeight() * currentScale);
            int webViewHeight = this.getHeight();
            int cutoff = height - webViewHeight - 10; // Don't be too strict on the cutoff point
            if (t >= cutoff) {
                // We need to know if it's necessary to show the accept checkbox. It should be visible only if it's not the first time that this dialog has been showed, so only
                // if the policies have been accepted previously. if we have the key stored, then, it's not the first time this dialog is being showed, so we must show the accept checkbox
                if(App.getInstance().containsKey(Constants.PRIVACY_POLICIES_ACCEPTED)){
                    acceptCheckbox.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    policiesWebView.loadUrl(ConfigManager.getInstance().getPrivacyUrl());
    LinearLayout.LayoutParams policiesWebViewLayoutParams =  new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,0);
    policiesWebViewLayoutParams.weight=1;
    policiesWebView.setLayoutParams(policiesWebViewLayoutParams);
    policiesWebView.setVisibility(View.GONE);
    ll.addView(policiesWebView);
    ll.addView(acceptCheckbox);

    final TextView readPolicies = new TextView(activity);
    LinearLayout.LayoutParams readPoliciesLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    readPoliciesLP.setMargins( Util.dpToPx(activity, 15), 0, Util.dpToPx(activity, 10), Util.dpToPx(activity, 30) );
    readPolicies.setPadding(0,0,0,Util.dpToPx(activity, 20));
    readPolicies.setTextColor(LIGHT_GRAY);
    readPolicies.setLayoutParams(readPoliciesLP);
    SpannableString content = new SpannableString(activity.getString(R.string.PLEASE_READ_POLICIES));
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    readPolicies.setText(content);
    readPolicies.setTextSize(16);
    readPolicies.setGravity(Gravity.LEFT);
    readPolicies.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
            title.setVisibility(View.GONE);
            policiesWebView.setVisibility(View.VISIBLE);
            readPolicies.setVisibility(View.GONE);
        }
    });
    ll.addView(readPolicies);

    // We need to know if we should treat this buttonas an agree button or a back button.
    // Agree mode: If it's the first time this dialog is being showed. Policies has not been accepted previously.
    // Back mode: If it's not the first time. The policies has been accepted previously.
    String buttonText = App.getInstance().containsKey(Constants.PRIVACY_POLICIES_ACCEPTED) == false ? activity.getString(R.string.AGREE) : activity.getString(R.string.BACK);

    builder.setPositiveButton(buttonText,
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(App.getInstance().containsKey(Constants.PRIVACY_POLICIES_ACCEPTED) == false) { //if agree mode
                    App.getInstance().storeBooleanValue(Constants.SEND_DATA_CHECKBOX, true);
                    App.getInstance().storeBooleanValue(Constants.PRIVACY_POLICIES_ACCEPTED, true);
                }

                dialogInterface.dismiss();
                if(runnable != null)
                    runnable.run();
            }
        }
    );

    // We will show close app button only if it's the first time we show this dialog.
    if(App.getInstance().containsKey(Constants.PRIVACY_POLICIES_ACCEPTED) == false)
        builder.setNegativeButton(R.string.CLOSE_APP,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    //launching navigator with non accept policies text
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String url = "https://myurl.com/no-terms.php?idApp={appId}";
                    url=GlobalVariablesManager.getInstance().replaceValues(url, false, false);
                    intent.setData(Uri.parse(URLParser.parse(url)));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    activity.startActivity(intent);

                    //App.getInstance().storeBooleanValue(Constants.PRIVACY_POLICIES_ACCEPTED, false);
                    SectionManager.getInstance().exit(false);
                    App.getInstance().clean();
                    activity.finish();
                }
            }
        );

    builder.setView(ll);
    final AlertDialog dialog = builder.create();
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    // This will set the color of negative button to a gray color
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface arg0) {
            Button buttonNegative = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            buttonNegative.setTextColor(LIGHT_GRAY);
        }
    });

    dialog.show();
}

来自 BadTokenException 的文档:

 Exception that is thrown when trying to add view whose
 {@link LayoutParams} {@link LayoutParams#token}
 is invalid.

此令牌已在其附加方法上提供给 activity,所以我猜您在某些情况下试图过早显示对话框。尝试 post post 块中的显示方法

我自己前阵子也犯过这个错误。以下是我从 Crashlytics 获得的有用见解:

"This crash is usually caused by your app trying to display a dialog using a previously-finished Activity as a context. For example, this can happen if an Activity triggers an AsyncTask that tries to display a dialog when it is finished, but the user navigates back from the Activity before the task is completed."

Crashlytics 建议的链接:
Android – Displaying Dialogs From Background Threads
Error : BinderProxy@45d459c0 is not valid; is your activity running?