前台服务概览
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
借助前台服务,您可以异步执行用户可感知到的操作。前台服务需要显示状态栏通知,让用户知道您的应用正在前台执行任务并消耗系统资源。
使用前台服务的应用示例包括:
- 一款音乐播放器应用,用于在前台服务中播放音乐。通知可能会显示当前正在播放的歌曲。
- 一款健身应用,在获得用户许可后,可在前台服务中记录用户跑步数据。通知可能会显示用户在当前健身会话期间行进的距离。
仅当应用需要执行可被用户注意到的任务时,才使用前台服务,即使在用户没有与应用直接互动时也是如此。如果操作的重要性较低,以至于您想使用最低优先级的通知,那么您可能需要使用其他后台工作选项。
本指南介绍了以下方面:
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-21。
[null,null,["最后更新时间 (UTC):2025-08-21。"],[],[],null,["# Foreground services overview\n\nForeground services let you asynchronously perform operations that are\nnoticeable to the user. Foreground services show a [status bar\nnotification](/develop/ui/views/notifications), to make users aware that your\napp is performing a task in the foreground and is consuming system resources.\n\nExamples of apps that use foreground services include the following:\n\n- A music player app that plays music in a foreground service. The notification might show the current song being played.\n- A fitness app that records a user's run in a foreground service, after receiving permission from the user. The notification might show the distance that the user has traveled during the current fitness session.\n\nOnly use a foreground service when your app needs to perform a task\nthat is noticeable by the user, even when they're not directly interacting with\nthe app. If the action is of low enough importance that you want to use a\nminimum-priority notification, you probably want to use a different\n[background work option](/develop/background-work/background-tasks).\n\nThis guide explains the following areas:\n\n- [Declare foreground services and request\n permissions](/develop/background-work/services/fgs/declare)\n- [Launch a foreground service](/develop/background-work/services/fgs/launch)\n- [Stop a foreground service](/develop/background-work/services/fgs/stop-fgs)\n- [Handle when a user stops an app that has a foreground\n service](/develop/background-work/services/fgs/handle-user-stopping)\n- [Restrictions on starting a foreground service from the background](/develop/background-work/services/fgs/restrictions-bg-start)\n- [Foreground service types](/develop/background-work/services/fgs/service-types)\n- [Foreground service timeout behavior](/develop/background-work/services/fgs/timeout)\n- [Foreground service troubleshooting](/develop/background-work/services/fgs/troubleshooting)\n- [Changes to foreground services](/develop/background-work/services/fgs/changes)"]]