Android前台服务

发布于 2024-12-03 12:39:44 字数 648 浏览 0 评论 0原文

故事如下:我创建了一个应用程序,该应用程序在启动时启动并按指定的时间间隔执行某些操作。为了实现这一目标,我正在创建一个服务,该服务使用 AlarmManager 创建重复事件,然后由完成繁重工作的 BroadcastReceiver 处理。当服务被销毁(用户选择退出应用程序)时,事件必须被取消,因此服务必须保留对用于启动它的相同 PendingIntent 的引用。

问题:服务必须调用 startForeground 以确保它不会终止,以便它可以维护对 PendingIntent 的引用。该通知始终出现在状态栏中,用户觉得很烦人(说实话,我也是)。

接下来做什么? 理想情况下,我正在寻找一种解决方案,将图标保留在状态栏中,但不会显示在下拉列表中。这样用户就会知道它正在运行,并且不会因为浪费空间而烦恼。

一些猜测:也许在重新创建引用时可以恢复服务中的引用?如果是这样,怎么办?这样我就可以避免使用 startForeground。但是,如何让图标进入状态栏呢?

或者也许有人有更好的解决方案?

Here's the story: I've created an application that starts at boot time and perform some action at specified interval. To achieve that I'm creating a service that uses an AlarmManager to create repeating event which is then handled by BroadcastReceiver which does the heavy work. When the service is destroyed (user choose to exit the application) the event has to be cancelled, so the service has to keep reference to the same PendingIntent that was used to start it.

The problem: Service has to call startForeground to ensure it doesn't die so it can maintain the reference to PendingIntent. The notification appears all the time in the status bar and users find it annoying (to be honest, me too).

What next? Ideally I'm looking for solution which will keep the icon in the status bar, but won't display in the drag-down list. This way the user will know it's running and won't be annoyed by waste of space.

Few guesses: Maybe it's possible to restore the reference in service, when it's recreated? If so, how? This way I could avoid using startForeground. But still, how to get the icon into statusbar?

Or maybe someone has a better solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寒冷纷飞旳雪 2024-12-10 12:39:44

首先,您不必一直保留 PendingIntent。如果您拥有所有必需的数据,您可以稍后重新创建它以取消通知 - 您只需使用完全相同的数据重新创建它即可。

First of all you don't have to hold on to PendingIntent all the time. If you have all the required data you can later re-create it to cancel the notification - you just have to re-create it with exactly the same data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文