我有在启动完成后激活的广播接收器。原因是我想在设备重启后重新安排所有警报。但是,我想显示一个对话框,询问用户是否要继续。这是代码
public class StartupAlarmReceiver extends BroadcastReceiver{
Context con;
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
con = context;
AlertDialog.Builder actionBuilder = new AlertDialog.Builder(context);
actionBuilder.setTitle("test");
actionBuilder.setMessage("Do you want to restart alarms?");
actionBuilder.setCancelable(false);
actionBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
new MyAsyncTask().execute();
}
})
.setNegativeButton("No" , new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = actionBuilder.create();
alert.show();
}
}
}
但是我得到了例外:
11-25 18:51:31.906: E/AndroidRuntime(1949): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
11-25 18:51:31.906: E/AndroidRuntime(1949): at android.view.ViewRootImpl.setView(ViewRootImpl.java:693)
11-25 18:51:31.906: E/AndroidRuntime(1949): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:313)
11-25 18:51:31.906: E/AndroidRuntime(1949): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
我想我知道原因,但我不知道如何解决。我认为(从 SO 中阅读)原因是对话框需要一个活动,因此可以显示它,并且由于我不在我的应用程序中,所以我没有活动。那么有没有办法在重启后显示对话框?我可以显示 Toast,但对话框失败
除非我的理论是错误的并且我错过了一个重点。请帮忙,谢谢