我接收推送通知时无法创建对话框

时间:2013-10-28 14:16:19

标签: android android-notifications android-dialog

每当我收到推送通知,并且我的应用程序可见时(onStart()/ onStop()对),我试图从GCMIntentService类向用户显示一个对话框。 (我还没有切换到下一个GCM,实际上我做了但是我遇到了问题,所以我换回了旧版本)

protected void onMessage(Context context, Intent intent)
{
    AlertDialog.Builder builder = new AlertDialog.Builder(context); //issue here

builder.setMessage("You have a notification").setTitle("Notification");
builder.setPositiveButton("dismiss",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});

AlertDialog dialog = builder.create();
dialog.show();
 } 

我得到的错误是

  

android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null不适用于应用程序

我知道这是一个上下文错误,并且在Google的文档等中写错了... 但是,每当收到通知时,显示对话的方式是什么?

1 个答案:

答案 0 :(得分:1)

不是使用对话框,而是创建活动并将其主题设置为Theme.dialog或其任何子项,然后从onMessage方法启动活动。

这样,您的活动将用于对话的目的,问题就会消失