android 应用程序(活动或服务)被终止时如何删除所有通知? [英] How to remove all notifications when an android app (activity or service) is killed?

查看:51
本文介绍了android 应用程序(活动或服务)被终止时如何删除所有通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在后台运行的带有 Activity 和 Intent 服务的应用.

I have an app with an activity and an intent service running in the background.

还有一个通知,其中显示了一个带有后台进程进度的进度条(它正在从服务器下载大量文件).

There's also a notification which shows a progress bar with the progress of the background process (it's downloading a lot of files from a server).

活动显示下载进度(用户在下载这些资产之前无法有意义地使用应用程序).当此活动关闭时,会显示带有进度条的通知.

The activity shows the download progress ( user can't meaningfully use the app before these assets are downloaded). When this activity is closed, the notification with the progress bar is shown.

我的问题:当应用程序通过任务管理器"被杀死时(可通过 android 4.0 上的右键访问,即带有两个矩形的那个),通知仍然存在.但它基本上是一个僵尸,因为用来更新它的服务已经死了.

My issue: When the application is killed via the "task manager" (accessible via right button on android 4.0, the one with the two rectangles), the notification is still there. But it's basically a zombie, because the service that used to update it is dead.

换一种方式:当我的应用程序被终止时,我如何删除一个(或所有)通知?

Put in a different way: How can I remove a (or all) notification(s) when my application is killed?

推荐答案

@Seepublic void onTaskRemoved(Intent rootIntent).如果服务当前正在运行并且用户已删除来自服务应用程序的任务,则会调用此方法.如果您设置了 ServiceInfo.FLAG_STOP_WITH_TASK 标志,那么您将不会收到此回调;相反,该服务将被简单地停止.

@See public void onTaskRemoved(Intent rootIntent). This is called if the service is currently running and the user has removed a task that comes from the service's application. If you have set ServiceInfo.FLAG_STOP_WITH_TASK flag then you will not receive this callback; instead, the service will simply be stopped.

您可以使用 cancelAll() 删除应用创建的所有通知:

You can remove all notifications that your app has created with cancelAll():

NotificationManager nManager = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
nManager.cancelAll();

根据 API 文档,这将

According to the API docs, this will

取消之前显示的所有通知.

Cancel all previously shown notifications.

以与 cancel(int id) 确实:

in the same way that cancel(int id) does:

取消之前显示的通知.如果它是暂时的,视图将被隐藏.如果它是持久的,它将从状态栏中删除.

Cancel a previously shown notification. If it's transient, the view will be hidden. If it's persistent, it will be removed from the status bar.

这篇关于android 应用程序(活动或服务)被终止时如何删除所有通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆