Android前台服务(Android foreground service)

编程入门 行业动态 更新时间:2024-10-15 16:23:44
Android前台服务(Android foreground service)

这是故事:我创建了一个在启动时启动并以指定间隔执行某些操作的应用程序。 为了实现这一点,我正在创建一个使用AlarmManager来创建重复事件的服务,然后由BroadcastReceiver处理,该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?

最满意答案

首先,您不必一直坚持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.

更多推荐

本文发布于:2023-08-01 00:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1351329.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前台   Android   service   foreground

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!