Android通知从未显示过

时间:2013-04-08 17:33:19

标签: android notifications

我想从服务创建通知。这是我的代码:

    private void showNotification(String text) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, PocketSaverActivity.class), 0);
    Notification.Builder builder = new Notification.Builder(this).setContentTitle("the title").setContentText(text)
            .setContentIntent(contentIntent).setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true);

    Notification notification = builder.getNotification();
    notificationManager.notify(R.drawable.ic_launcher, notification);
}

但是这段代码会给我一个警告04-08 20:25:49.030: W/NotificationManager(1670): notify: id corrupted: sent 12345, got back 0 并且没有显示。我不知道是什么问题。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

在这一行:

Notification.Builder builder = new Notification.Builder(this)
    .setContentTitle("the title")
    .setContentText(text)
    .setContentIntent(contentIntent)
    .setSmallIcon(R.drawable.ic_launcher)
    .setAutoCancel(true);

您需要在结尾添加.build(),如下所示:

Notification notification = new Notification.Builder(this)
    .setContentTitle("the title")
    .setContentText(text)
    .setContentIntent(contentIntent)
    .setSmallIcon(R.drawable.ic_launcher)
    .setAutoCancel(true)
    .build();

此外,Notification notification = builder.getNotification();不是必需的,只需使用已链接的已建立通知。

您可以在the documentation

中看到更通用的示例