安卓.view.WindowManager$BadTokenException : Unable to add window while showing a AlertDialog from broadcast receiver

标签 android android-alertdialog

我已经设置了警报管理器我想在 BroadcastReceiver 的 onReceive 方法中显示一个对话框。

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Utils.getINSTANCE().statusCheck(context);
    }
}

这里是statuscheck方法

    public void statusCheck(Context context) {
    final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps(context);

    }
}
private void buildAlertMessageNoGps(final Context context) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    context. startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

我在 alert.show() 上遇到问题 token null

java.lang.RuntimeException: Unable to start receiver com.coin.etheriumclassic.AlarmReceiver: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

我们该怎么做?如果我们必须在 Broadcastreceiver 中显示简单的对话框(我在 broadcastreceiver 中这样做是因为我必须在设备打开时显示对话)

最佳答案

您只能显示来自 ActivityAlertDialog,而不是 BroadcastReceiver

可以BroadcastReceiver 启动一个 Activity ,因此您可以创建一个带有对话框主题(例如 Theme.Material.Dialog )的 Activity ,所以它的样式如下一个对话框。

但请注意,在设备启动时显示对话框对用户来说相当不利,更不用说不切实际了(例如,设备有锁屏)。考虑改为显示 Notification

关于安卓.view.WindowManager$BadTokenException : Unable to add window while showing a AlertDialog from broadcast receiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49592218/

相关文章:

尝试构建 React Native 0.59 应用程序时与 AndroidX 相关的 AndroidManifest 错误

安卓单元测试: how to clear SharedPreferences

android - alertdialog 正/负按钮与全屏对话框 fragment 中的父级不匹配

android - 带有列表选择项的警告框保持为空

android - 使用带有 Holo 主题的 Sherlock 显示 AlertDialog?

java - Java Android开发 “Failure in SSL library, usually a protocol”

android - 最佳光标使用

android - AlertDialog.Builder 不在 Fragment 中显示来自 setUserVisibleHint(boolean) 的按钮

Android取消具有自定义布局的alertDialog

android - 无法在 dialogfragment 中的按钮上获取指针