【问题标题】:android.view.WindowManager$BadTokenException: Unable to add window while showing a AlertDialog from broadcast receiverandroid.view.WindowManager$BadTokenException:在显示来自广播接收器的 AlertDialog 时无法添加窗口
【发布时间】:2018-04-01 05:04:21
【问题描述】:

我已经设置了警报管理器,我想在 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);
    }
}

这里是状​​态检查方法

    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() 上遇到问题令牌 null

java.lang.RuntimeException: Unable to start receiver com.coin.etheriumclassic.AlarmReceiver: android.view.WindowManager$BadTokenException: Unable to add window -- token null 不适用于应用程序

我们怎样才能做到这一点?如果我们必须在广播接收器中显示简单的对话框(我在广播接收器中这样做,因为我必须在设备打开时显示对话)

【问题讨论】:

  • 使用系统警报亲爱的

标签: android android-alertdialog


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢您了解 Activity 和 AlertDialog 之间的关系。非常感谢。
猜你喜欢
  • 2013-09-10
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 2012-04-21
  • 1970-01-01
相关资源
最近更新 更多