To help developers be more intentional with defining user-facing foreground
services, Android 10 introduced the android:foregroundServiceType
attribute within the <service>
element.
If your app targets Android 14, it must specify appropriate foreground service types. As in previous versions of Android, multiple types can be combined. This list shows the foreground service types to choose from:
camera
connectedDevice
dataSync
health
location
mediaPlayback
mediaProjection
microphone
phoneCall
remoteMessaging
shortService
specialUse
systemExempted
If a use case in your app isn't associated with any of these types, we strongly recommend that you migrate your logic to use WorkManager or user-initiated data transfer jobs.
The health, remoteMessaging, shortService, specialUse
, and systemExempted
types are new in Android 14.
The following code snippet provides an example of a foreground service type declaration in the manifest:
<manifest ...>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<application ...>
<service
android:name=".MyMediaPlaybackService"
android:foregroundServiceType="mediaPlayback"
android:exported="false">
</service>
</application>
</manifest>
If an app that targets Android 14 doesn't define types for a given service in
the manifest, then the system will raise MissingForegroundServiceTypeException
upon calling startForeground()
for that service.
הצהרת הרשאה חדשה לשימוש בסוגי שירותים שפועלים בחזית
If apps that target Android 14 use a foreground service, they must declare a specific permission, based on the foreground service type, that Android 14 introduces. These permissions appear in the sections labeled "permission that you must declare in your manifest file" in the intended use cases and enforcement for each foreground service type section on this page.
All of the permissions are defined as normal permissions and are granted by default. Users cannot revoke these permissions.
הכללת סוג השירות שפועל בחזית בזמן הריצה
对于启动前台服务的应用,最佳实践是使用 startForeground()
的 ServiceCompat
版本(在 androidx-core 1.12 及更高版本中提供),并在其中传入前台服务类型的按位整数。您可以选择传递一个或多个类型值。
通常,您应仅声明特定用例所需的类型。这样可以更轻松地满足系统对每种前台服务类型的预期。如果某项前台服务以多种类型启动,则该前台服务必须遵守所有类型的平台强制执行要求。
ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)
如果在调用中未指定前台服务类型,则类型默认为清单中定义的值。如果您未在清单中指定服务类型,系统会抛出 MissingForegroundServiceTypeException
。
如果前台服务在启动后需要新权限,您应再次调用 startForeground()
并添加新的服务类型。例如,假设一款健身应用运行一项始终需要 location
信息但可能不需要 media
权限的跑步跟踪器服务。您需要在清单中同时声明 location
和 mediaPlayback
。如果用户开始跑步,只希望跟踪其位置信息,您的应用应调用 startForeground()
,并仅传递 location
服务类型。然后,如果用户想开始播放音频,请再次调用 startForeground()
并传递 location|mediaPlayback
。
בדיקות זמן ריצה של המערכת
The system checks for proper use of foreground service types and confirms that
the app has requested the proper runtime permissions or uses the required APIs.
For instance, the system expects apps that use the foreground service type
FOREGROUND_SERVICE_TYPE_LOCATION
type to request either
ACCESS_COARSE_LOCATION
or ACCESS_FINE_LOCATION
.
This implies that apps must follow a very specific
order of operations when requesting permissions from the user and starting
foreground services. Permissions must be requested and granted before the
app attempts to call startForeground()
. Apps that request the appropriate
permissions after the foreground service has been started must change this order
of operations and request the permission before starting the foreground service.
The specifics of platform enforcement appear in the sections labeled "runtime requirements" in the intended use cases and enforcement for each foreground service type section on this page.
תרחישים לדוגמה ואכיפה שמיועדים לכל סוג של שירות שפועל בחזית
In order to use a given foreground service type, you must declare a particular permission in your manifest file, you must fulfill specific runtime requirements, and your app must fulfill one of the intended sets of use cases for that type. The following sections explain the permission that you must declare, the runtime prerequisites, and the intended use cases for each type.
מצלמה
- Foreground service type to declare in manifest under
android:foregroundServiceType
camera
- Permission to declare in your manifest
FOREGROUND_SERVICE_CAMERA
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_CAMERA
- Runtime prerequisites
Request and be granted the
CAMERA
runtime permissionNote: The
CAMERA
runtime permission is subject to while-in-use restrictions. For this reason, you cannot create acamera
foreground service while your app is in the background, with a few exceptions. For more information, see Restrictions on starting foreground services that need while-in-use permissions.- Description
Continue to access the camera from the background, such as video chat apps that allow for multitasking.
המכשיר המחובר
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
connectedDevice
- 在清单中声明的权限
FOREGROUND_SERVICE_CONNECTED_DEVICE
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
- 运行时前提条件
必须至少满足以下其中一个条件:
在清单中至少声明以下其中一项权限:
至少请求并被授予以下其中一项运行时权限:
- 说明
与需要蓝牙、NFC、IR、USB 或网络连接的外部设备进行互动。
- 替代方案
如果您的应用需要向外部设备持续传输数据,请考虑改用配套设备管理器。使用配套设备感知 API,可帮助您的应用在配套设备在范围内时保持运行。
如果您的应用需要扫描蓝牙设备,请考虑改用 Bluetooth Scan API。
סנכרון נתונים
- Foreground service type to declare in manifest under
android:foregroundServiceType
dataSync
- Permission to declare in your manifest
FOREGROUND_SERVICE_DATA_SYNC
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_DATA_SYNC
- Runtime prerequisites
- None
- Description
Data transfer operations, such as the following:
- Data upload or download
- Backup-and-restore operations
- Import or export operations
- Fetch data
- Local file processing
- Transfer data between a device and the cloud over a network
- Alternatives
See Alternatives to data sync foreground services for detailed information.
בריאות
- Foreground service type to declare in manifest under
android:foregroundServiceType
health
- Permission to declare in your manifest
FOREGROUND_SERVICE_HEALTH
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_HEALTH
- Runtime prerequisites
At least one of the following conditions must be true:
Declare the
HIGH_SAMPLING_RATE_SENSORS
permission in your manifest.Request and be granted at least one of the following runtime permissions:
BODY_SENSORS
on API level 35 and lowerREAD_HEART_RATE
READ_SKIN_TEMPERATURE
READ_OXYGEN_SATURATION
ACTIVITY_RECOGNITION
Note: The
BODY_SENSORS
and sensor-based READ runtime permissions are subject to while-in-use restrictions. For this reason, you cannot create ahealth
foreground service that uses body sensors while your app is in the background unless you've been granted theBODY_SENSORS_BACKGROUND
(API level 33 to 35) orREAD_HEALTH_DATA_IN_BACKGROUND
(API level 36 and higher) permissions. For more information, see Restrictions on starting foreground services that need while-in-use permissions.- Description
Any long-running use cases to support apps in the fitness category such as exercise trackers.
מיקום
- Foreground service type to declare in manifest under
android:foregroundServiceType
location
- Permission to declare in your manifest
FOREGROUND_SERVICE_LOCATION
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_LOCATION
- Runtime prerequisites
The user must have enabled location services and the app must be granted at least one of the following runtime permissions:
Note: In order to check that the user has enabled location services as well as granted access to the runtime permissions, use
PermissionChecker#checkSelfPermission()
Note: The location runtime permissions are subject to while-in-use restrictions. For this reason, you cannot create a
location
foreground service while your app is in the background, unless you've been granted theACCESS_BACKGROUND_LOCATION
runtime permission. For more information, see Restrictions on starting foreground services that need while-in-use permissions.- Description
Long-running use cases that require location access, such as navigation and location sharing.
- Alternatives
If your app needs to be triggered when the user reaches specific locations, consider using the geofence API instead.
מדיה
- Foreground service type to declare in manifest under
android:foregroundServiceType
mediaPlayback
- Permission to declare in your manifest
FOREGROUND_SERVICE_MEDIA_PLAYBACK
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
- Runtime prerequisites
- None
- Description
- Continue audio or video playback from the background. Support Digital Video Recording (DVR) functionality on Android TV.
- Alternatives
- If you're showing picture-in-picture video, use Picture-in-Picture mode.
הקרנת מדיה
- Foreground service type to declare in manifest under
android:foregroundServiceType
mediaProjection
- Permission to declare in your manifest
FOREGROUND_SERVICE_MEDIA_PROJECTION
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
- Runtime prerequisites
Call the
createScreenCaptureIntent()
method before starting the foreground service. Doing so shows a permission notification to the user; the user must grant the permission before you can create the service.After you have created the foreground service, you can call
MediaProjectionManager.getMediaProjection()
.- Description
Project content to non-primary display or external device using the
MediaProjection
APIs. This content doesn't have to be exclusively media content.- Alternatives
To stream media to another device, use the Google Cast SDK.
מיקרופון
- Foreground service type to declare in manifest under
android:foregroundServiceType
microphone
- Permission to declare in your manifest
FOREGROUND_SERVICE_MICROPHONE
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_MICROPHONE
- Runtime prerequisites
Request and be granted the
RECORD_AUDIO
runtime permission.Note: The
RECORD_AUDIO
runtime permission is subject to while-in-use restrictions. For this reason, you cannot create amicrophone
foreground service while your app is in the background, with a few exceptions. For more information, see Restrictions on starting foreground services that need while-in-use permissions.- Description
Continue microphone capture from the background, such as voice recorders or communication apps.
שיחת טלפון
- Foreground service type to declare in manifest under
android:foregroundServiceType
phoneCall
- Permission to declare in your manifest
FOREGROUND_SERVICE_PHONE_CALL
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_PHONE_CALL
- Runtime prerequisites
At least one of these conditions must be true:
- App has declared the
MANAGE_OWN_CALLS
permission in its manifest file.
- App has declared the
- App is the default dialer app through the
ROLE_DIALER
role.
- App is the default dialer app through the
- Description
Continue an ongoing call using the
ConnectionService
APIs.- Alternatives
If you need to make phone, video, or VoIP calls, consider using the
android.telecom
library.Consider using
CallScreeningService
to screen calls.
העברת הודעות מרחוק
- Foreground service type to declare in manifest under
android:foregroundServiceType
remoteMessaging
- Permission to declare in your manifest
FOREGROUND_SERVICE_REMOTE_MESSAGING
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
- Runtime prerequisites
- None
- Description
- Transfer text messages from one device to another. Assists with continuity of a user's messaging tasks when they switch devices.
שירות מקוצר
- סוג השירות שפועל בחזית שצריך להצהיר עליו במניפסט בקטע
android:foregroundServiceType
shortService
- הרשאה להצהרה במניפסט
- ללא
- קבוע להעברה אל
startForeground()
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
- דרישות מוקדמות בסביבת זמן הריצה
- ללא
- תיאור
לסיים במהירות עבודה קריטית שלא ניתן להפריע לה או לדחות אותה.
לסוג הזה יש כמה מאפיינים ייחודיים:
- אפשר להריץ אותו רק לפרק זמן קצר (כ-3 דקות).
- אין תמיכה בשירותי חזית דביקים.
- אי אפשר להפעיל שירותים אחרים שפועלים בחזית.
- לא נדרשת הרשאה ספציפית לסוג, אבל עדיין נדרשת ההרשאה
FOREGROUND_SERVICE
. - אפשר לשנות את
shortService
לסוג שירות אחר רק אם האפליקציה עומדת כרגע בדרישות להפעלת שירות חדש בחזית. - שירות שפועל בחזית יכול לשנות את הסוג שלו ל-
shortService
בכל שלב, ובאותו רגע מתחילה תקופת הזמן הקצובה.
הזמן הקצוב לתפוגה של shortService מתחיל מהרגע שבו מתבצעת הקריאה ל-
Service.startForeground()
. האפליקציה אמורה לבצע קריאה ל-Service.stopSelf()
או ל-Service.stopForeground()
לפני שהזמן יפוג. אחרת,Service.onTimeout()
החדש ייוצר, ויינתן לאפליקציות הזדמנות קצרה להתקשר ל-stopSelf()
או ל-stopForeground()
כדי להפסיק את השירות שלהן.זמן קצר אחרי הקריאה ל-
Service.onTimeout()
, האפליקציה נכנסת למצב שמאוחסן במטמון והיא כבר לא נחשבת לפעילה בחזית, אלא אם המשתמש מבצע אינטראקציה פעילה עם האפליקציה. זמן קצר אחרי שהאפליקציה מאוחסנת במטמון והשירות לא הופסק, האפליקציה מקבלת אירוע ANR. בהודעת ה-ANR מוזכרFOREGROUND_SERVICE_TYPE_SHORT_SERVICE
. לכן, מומלץ להטמיע את פונקציית ה-callbackService.onTimeout()
.קריאת החזרה (call back)
Service.onTimeout()
לא קיימת ב-Android מגרסה 13 ומטה. אם אותו שירות פועל במכשירים כאלה, הוא לא מקבל זמן קצוב לתפוגה ולא מתרחשת בו בעיה מסוג ANR. חשוב לוודא שהשירות יפסיק לפעול ברגע שהוא יסיים את משימת העיבוד, גם אם הוא עדיין לא קיבל את הקריאה החוזרת (callback) שלService.onTimeout()
.חשוב לציין שאם לא יתקיים הזמן הקצוב לתפוגה של
shortService
, תופיע באפליקציה שגיאת ANR גם אם פועלות בה שירותים חוקיים אחרים בחזית או תהליכים אחרים במחזור החיים של האפליקציה.אם אפליקציה גלויה למשתמש או עומדת באחד מההחרגות שמאפשרות להפעיל שירותים שפועלים בחזית מהרקע, קריאה חוזרת ל-
Service.StartForeground()
עם הפרמטרFOREGROUND_SERVICE_TYPE_SHORT_SERVICE
מאריכה את הזמן הקצוב לתפוגה ב-3 דקות נוספות. אם האפליקציה לא גלויה למשתמש ולא עומדת באחד מההחרגות, כל ניסיון להפעיל שירות נוסף שפועל בחזית, ללא קשר לסוג שלו, יגרום לForegroundServiceStartNotAllowedException
.אם משתמש משבית את אופטימיזציית הסוללה באפליקציה, היא עדיין מושפעת מזמן הקצאת הזמן הקצוב לתפוגה של shortService FGS.
אם מפעילים שירות שפועל בחזית שכולל את הסוג
shortService
וגם סוג אחר של שירות שפועל בחזית, המערכת מתעלמת מהצהרת הסוגshortService
. עם זאת, השירות עדיין צריך לעמוד בדרישות המוקדמות של הסוגים האחרים שצוינו. מידע נוסף זמין במסמכי העזרה של שירותי חזית.
שימוש מיוחד
- Foreground service type to declare in manifest under
android:foregroundServiceType
specialUse
- Permission to declare in your manifest
FOREGROUND_SERVICE_SPECIAL_USE
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
- Runtime prerequisites
- None
- Description
Covers any valid foreground service use cases that aren't covered by the other foreground service types.
In addition to declaring the
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
foreground service type, developers should declare use cases in the manifest. To do so, they specify the<property>
element within the<service>
element. These values and corresponding use cases are reviewed when you submit your app in the Google Play Console. The use cases you provide are free-form, and you should make sure to provide enough information to let the reviewer see why you need to use thespecialUse
type.<service android:name="fooService" android:foregroundServiceType="specialUse"> <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="explanation_for_special_use"/> </service>
פטור מהמערכת
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
systemExempted
- 在清单中声明的权限
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
- 运行时前提条件
- 无
- 说明
为系统应用和特定系统集成预留,使其能继续使用前台服务。
如需使用此类型,应用必须至少满足以下条件之一:
- 设备处于演示模式状态
- 应用是设备所有者
- 应用是性能分析器所有者
- 属于具有
ROLE_EMERGENCY
角色的安全应用 - 属于设备管理应用
- 具有
SCHEDULE_EXACT_ALARM
或USE_EXACT_ALARM
权限且使用前台服务在后台继续闹钟(包括仅振动闹钟)的应用。 VPN 应用(使用设置 > 网络和互联网 > VPN 进行配置)
否则,声明此类型会导致系统抛出
ForegroundServiceTypeNotAllowedException
。
אכיפת המדיניות של Google Play בנושא שימוש בסוגי שירותים שפועלים בחזית
如果您的应用以 Android 14 或更高版本为目标平台,您需要在 Play 管理中心的“应用内容”页面(政策 > 应用内容)中声明应用的前台服务类型。如需详细了解如何在 Play 管理中心内声明前台服务类型,请参阅了解前台服务和全屏 intent 要求。