当应用程序从“最近记录(内存)列表中删除时取消通知

问题描述 投票:0回答:2

我正在使用显示正在进行的通知的服务。当应用正常关闭时,通知会消失。但是,如果用户将其从最近的列表应用程序中删除,则该应用程序将关闭并停止该服务。但是,该通知仍然出现。这不是良好的用户体验。

注意:我尝试使用onTaskRemoved(),但根本没有调用它。

从最近的列表中删除应用程序后,如何删除通知。

更新:我注意到当该应用程序从最近的应用程序中删除或从其他应用程序中删除时,将调用以下3行。

11-27 11:44:05.097 3916-4157/? D/StatusBar: onNotificationRemoved:  Key: 
0|com.example.player|888|null|10525


11-27 11:44:05.107 3916-3916/? D/PhoneStatusBar: removeNotification key=android.os.Binder@2e604ccc keyCode=778063052 old=StatusBarNotification(pkg=com.example.player user=UserHandle{0} id=888 tag=null score=0 key=0|com.example.player|888|null|10525: Notification(pri=0 contentView=com.example.player/0x109008a vibrate=null sound=null defaults=0x0 flags=0x2 color=0xff40444a category=service actions=3 vis=PUBLIC))


11-27 11:44:05.137 4759-4759/? I/Launcher.ApplicationsMessage: update com.example.player/ to null

但是,在我的应用中,这3行代码是在应用被杀死时调用的,而不是从最新记录中删除。我想这可能是个问题(我错过了一些东西)。

android service notifications android-mediaplayer android-notifications
2个回答
0
投票

使用以下代码取消通知:

NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);

在此代码中,始终有用于通知的相同ID。如果您有需要取消的其他通知,并且必须保存用于创建通知的ID。


0
投票

最后,我得到了解决方案。

我在构建通知时错过了启动前台服务。

添加了这两行,并且当应用程序从最近的列表中删除/终止时,通知会自动删除。

onBuildNotification():

startForeground(NOTIFICATION_ID, notification);

onRemovenotification():

 stopForeground(true);
© www.soinside.com 2019 - 2024. All rights reserved.