2013-04-08 162 views
0

我想從服務創建通知。在這裏我的代碼:Android通知從未顯示

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 並沒有顯示。我不知道是什麼問題。有人可以幫忙嗎?

+0

一個更通用的例子你看這個? http://stackoverflow.com/questions/11057250/notification-from-a-service – Codeman 2013-04-08 17:37:05

回答

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