6

我一直在尝试了几个小时,除去使用永久通知由服务设置:NotificationManager.cancel()不为我工作

startForeground(1337, notification); 

我用取消它的代码:

NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
nManager.cancel(1337); // cancel existing service notification, doesn't take effect 
nManager.cancelAll(); //surpluous, but also doesn't take effect 

我在这里错过了什么?我很困惑。

为了说明为什么我这样做:服务以默认持久通知开始。当我的应用程序运行时,它需要将此通知替换为另一通知。然而,在现有的Notification上使用notify()可以完美地工作,但我需要它为新的Notification显示Ticker文本。这就是为什么我决定删除现有的通知(使用上面的代码),创建一个新通知,然后再次拨打startForeground()并将新的通知传递给它,以便我的服务持续存在。

+0

您试图删除从其他应用程序启动的通知? – matt5784 2012-07-08 23:18:51

+0

不,这是相同的应用程序 – slinden77 2012-07-08 23:45:34

回答

11

问题是,您使用startForeground()以间接方式发出通知。您不能仅仅因为系统在启动前台服务时坚持要提供通知的相同原因而取消该通知。只要您的前台服务正在运行,该通知就会在那里。

在大多数情况下,服务真的不应该在前台。如果您可以为您的服务使用正常优先级,则可以正常启动和停止您的通知。

如果你确实在做一些确实需要前台服务的东西,并且如果你真的想向用户显示一个行情文本,我相信你唯一的选择是发布另一个通知。

+7

他们应该真的把它放在文档中,或者当它尝试时它会抛出一个错误... – slinden77 2012-07-09 00:02:55

6

您可以随时通过callng stopForeground(boolean removeNotification)从前台服务中删除通知。然后服务退出其foregroundState,并且当需要内存时可以再次被系统杀死。

0

您可以通过传递一个空的生成器来更新通知。

if(showNotification){ 
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) 
      .setVisibility(Notification.VISIBILITY_SECRET) 
      .setSmallIcon(R.mipmap.ic_spotify_white_24dp) 
      .setTicker("Playing Now") 
      .setContentTitle("Spotify") 
      .setContentText("Preview"); 
    return mBuilder; 
}else{ 
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); 
    return mBuilder; 
}