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.
Neue Berechtigung zur Verwendung von Typen von Diensten im Vordergrund deklarieren
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.
Typ des Diensts im Vordergrund während der Laufzeit einschließen
The best practice for applications starting foreground services is to use the
ServiceCompat
version of startForeground()
(available in androidx-core
1.12 and higher) where you pass in a bitwise
integer of foreground service types. You can choose to pass one or more type
values.
Usually, you should declare only the types required for a particular use case. This makes it easier to meet the system's expectations for each foreground service type. In cases where a foreground service is started with multiple types, then the foreground service must adhere to the platform enforcement requirements of all types.
ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)
If the foreground service type is not specified in the call, the type defaults
to the values defined in the manifest. If you didn't specify the service
type in the manifest, the system throws
MissingForegroundServiceTypeException
.
If the foreground service needs new permissions after you launch it, you
should call startForeground()
again and add the new service types. For
example, suppose a fitness app runs a running-tracker service that always needs
location
information, but might or might not need media
permissions. You
would need to declare both location
and mediaPlayback
in the manifest. If a
user starts a run and just wants their location tracked, your app should call
startForeground()
and pass just the location
service type. Then, if the user
wants to start playing audio, call startForeground()
again and pass
location|mediaPlayback
.
Systemlaufzeitprüfungen
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.
Vorgesehene Anwendungsfälle und Erzwingung für jeden Dienst im Vordergrund
Wenn Sie einen bestimmten Diensttyp im Vordergrund verwenden möchten, müssen Sie in Ihrer Manifestdatei eine bestimmte Berechtigung deklarieren, bestimmte Laufzeitanforderungen erfüllen und Ihre App muss einen der beabsichtigten Anwendungsfälle für diesen Typ erfüllen. In den folgenden Abschnitten werden die Berechtigung, die Sie deklarieren müssen, die Laufzeitvoraussetzungen und die beabsichtigten Anwendungsfälle für jeden Typ erläutert.
Kamera
- 要在
android:foregroundServiceType
下在清单中声明的前台服务类型 camera
- 在清单中声明的权限
FOREGROUND_SERVICE_CAMERA
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_CAMERA
- 运行时前提条件
请求并获得
CAMERA
运行时权限注意:
CAMERA
运行时权限受使用时限制的约束。因此,除少数例外情况外,您无法在应用在后台运行时创建camera
前台服务。如需了解详情,请参阅与启动需要“使用时”权限的前台服务相关的限制。- 说明
继续在后台访问相机,例如支持多任务的视频聊天应用。
Verbundenes Gerät
- Foreground service type to declare in manifest under
android:foregroundServiceType
connectedDevice
- Permission to declare in your manifest
FOREGROUND_SERVICE_CONNECTED_DEVICE
- Constant to pass to
startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
- Runtime prerequisites
At least one of the following conditions must be true:
Declare at least one of the following permissions in your manifest:
Request and be granted at least one of the following runtime permissions:
- Description
Interactions with external devices that require a Bluetooth, NFC, IR, USB, or network connection.
- Alternatives
If your app needs to do continuous data transfer to an external device, consider using the companion device manager instead. Use the companion device presence API to help your app stay running while the companion device is in range.
If your app needs to scan for bluetooth devices, consider using the Bluetooth scan API instead.
Datensynchronisierung
- Typ des Dienstes im Vordergrund, der im Manifest unter
android:foregroundServiceType
dataSync
- Berechtigung, die in Ihrem Manifest deklariert werden muss
FOREGROUND_SERVICE_DATA_SYNC
- Konstante, die an
startForeground()
übergeben werden soll FOREGROUND_SERVICE_TYPE_DATA_SYNC
- Laufzeitvoraussetzungen
- Keine
- Beschreibung
Datenübertragungsvorgänge, z. B.:
- Datenupload oder -download
- Sicherungs- und Wiederherstellungsvorgänge
- Import- oder Exportvorgänge
- Daten abrufen
- Lokale Dateiverarbeitung
- Daten über ein Netzwerk zwischen einem Gerät und der Cloud übertragen
- Alternativen
Ausführliche Informationen finden Sie unter Alternativen zu Diensten im Vordergrund für die Datensynchronisierung.
Zustand
- Typ des Diensts im Vordergrund, der im Manifest unter
android:foregroundServiceType
health
- Berechtigung, die in Ihrem Manifest deklariert werden muss
FOREGROUND_SERVICE_HEALTH
- Konstante, die an
startForeground()
übergeben werden soll FOREGROUND_SERVICE_TYPE_HEALTH
- Laufzeitvoraussetzungen
Mindestens eine der folgenden Bedingungen muss erfüllt sein:
Deklarieren Sie die Berechtigung
HIGH_SAMPLING_RATE_SENSORS
in Ihrem Manifest.Sie müssen mindestens eine der folgenden Laufzeitberechtigungen anfordern und erhalten:
BODY_SENSORS
auf API-Ebene 35 und niedrigerREAD_HEART_RATE
READ_SKIN_TEMPERATURE
READ_OXYGEN_SATURATION
ACTIVITY_RECOGNITION
Hinweis:Die Laufzeitberechtigungen
BODY_SENSORS
und die sensorbasierten LESE-Berechtigungen unterliegen Einschränkungen bei der Verwendung. Aus diesem Grund können Sie nur dann einenhealth
-Dienst im Vordergrund erstellen, der Körpersensoren verwendet, während Ihre App im Hintergrund ausgeführt wird, wenn Sie die BerechtigungenBODY_SENSORS_BACKGROUND
(API-Level 33 bis 35) oderREAD_HEALTH_DATA_IN_BACKGROUND
(API-Level 36 und höher) haben. Weitere Informationen finden Sie unter Einschränkungen beim Starten von Diensten im Vordergrund, für die Berechtigungen für die Nutzung erforderlich sind.- Beschreibung
Alle lang laufenden Anwendungsfälle zur Unterstützung von Apps in der Kategorie „Fitness“, z. B. Trainings-Tracker.
Standort
- 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.
Medien
- Typ des Dienstes im Vordergrund, der im Manifest unter
android:foregroundServiceType
mediaPlayback
- Berechtigung, die in Ihrem Manifest deklariert werden muss
FOREGROUND_SERVICE_MEDIA_PLAYBACK
- Konstante, die an
startForeground()
übergeben werden soll FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
- Laufzeitvoraussetzungen
- Keine
- Beschreibung
- Audio- oder Videowiedergabe im Hintergrund fortsetzen. Unterstützung der Funktion „Digitaler Videorekorder“ (DVR) auf Android TV.
- Alternativen
- Wenn Sie ein Bild-im-Bild-Video anzeigen, verwenden Sie den Bild-im-Bild-Modus.
Medienprojektion
- Typ des Dienstes im Vordergrund, der im Manifest unter
android:foregroundServiceType
mediaProjection
- Berechtigung, die in Ihrem Manifest deklariert werden muss
FOREGROUND_SERVICE_MEDIA_PROJECTION
- Konstante, die an
startForeground()
übergeben werden soll FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
- Laufzeitvoraussetzungen
Rufen Sie die Methode
createScreenCaptureIntent()
auf, bevor Sie den Dienst im Vordergrund starten. Daraufhin wird dem Nutzer eine Berechtigungsbenachrichtigung angezeigt. Der Nutzer muss die Berechtigung erteilen, bevor Sie den Dienst erstellen können.Nachdem Sie den Dienst im Vordergrund erstellt haben, können Sie
MediaProjectionManager.getMediaProjection()
aufrufen.- Beschreibung
Übertragung von Inhalten mit
MediaProjection
APIs auf nicht primäre Displays oder externe Geräte. Diese Inhalte müssen nicht ausschließlich Medieninhalte sein.- Alternativen
Wenn Sie Medien auf ein anderes Gerät streamen möchten, verwenden Sie das Google Cast SDK.
Mikrofon
- 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.
Telefonanruf
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
phoneCall
- 在清单中声明的权限
FOREGROUND_SERVICE_PHONE_CALL
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_PHONE_CALL
- 运行时前提条件
必须至少满足以下其中一个条件:
- 应用已在其清单文件中声明
MANAGE_OWN_CALLS
权限。
- 应用已在其清单文件中声明
- 应用是通过
ROLE_DIALER
角色的默认拨号器应用。
- 应用是通过
- 说明
使用
ConnectionService
API 继续当前通话。- 替代方案
如果您需要拨打电话、视频通话或 VoIP 通话,不妨考虑使用
android.telecom
库。考虑使用
CallScreeningService
来过滤来电。
Remote-Messaging
- 要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
remoteMessaging
- 在清单中声明的权限
FOREGROUND_SERVICE_REMOTE_MESSAGING
- 要传递给
startForeground()
的常量 FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
- 运行时前提条件
- 无
- 说明
- 将短信从一台设备转移到另一台设备。在用户切换设备时,帮助确保用户消息任务的连续性。
Kurzer Fahrbetrieb
- 要在清单中的以下位置声明的前台服务类型
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
。出于这些原因,实现Service.onTimeout()
回调被视为一种最佳实践。Android 13 及更低版本中不存在
Service.onTimeout()
回调。如果同一服务在此类设备上运行,则不会出现超时,也不会发生 ANR。确保您的服务在完成处理任务后立即停止,即使它尚未收到Service.onTimeout()
回调也是如此。请务必注意,如果未遵循
shortService
的超时设置,即使应用还有其他有效的前台服务或其他应用生命周期进程,应用也会遇到 ANR。如果应用对用户可见,或满足允许从后台启动前台服务的某一豁免条件,则使用
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
参数再次调用Service.StartForeground()
会将超时时间再延长 3 分钟。如果应用对用户不可见且不满足其中一个豁免条件,则尝试启动其他前台服务(无论其类型如何)都会导致ForegroundServiceStartNotAllowedException
。即使用户为您的应用停用电池优化功能,仍然会受到 shortService FGS 的影响。
如果您启动包含
shortService
类型和另一个前台服务类型的前台服务,系统会忽略shortService
类型声明。不过,该服务仍必须遵守其他声明类型的先决条件。如需了解详情,请参阅前台服务文档。
Spezielle Anwendungsfälle
- Typ des Diensts im Vordergrund, der im Manifest unter
android:foregroundServiceType
specialUse
- Berechtigung, die in Ihrem Manifest deklariert werden muss
FOREGROUND_SERVICE_SPECIAL_USE
- Konstante, die an
startForeground()
übergeben werden soll FOREGROUND_SERVICE_TYPE_SPECIAL_USE
- Laufzeitvoraussetzungen
- Keine
- Beschreibung
Deckt alle gültigen Anwendungsfälle für Dienste im Vordergrund ab, die nicht von den anderen Typen abgedeckt werden.
Neben der Deklarierung des
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
Typs von Diensten im Vordergrund sollten Entwickler Anwendungsfälle im Manifest deklarieren. Dazu geben sie das<property>
-Element innerhalb des Elements<service>
an. Diese Werte und die entsprechenden Anwendungsfälle werden geprüft, wenn Sie Ihre App in der Google Play Console einreichen. Die von Ihnen angegebenen Anwendungsfälle sind kostenlos formuliert. Sie sollten jedoch genügend Informationen angeben, damit die Prüfer nachvollziehen können, warum Sie denspecialUse
-Typ verwenden müssen.<service android:name="fooService" android:foregroundServiceType="specialUse"> <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="explanation_for_special_use"/> </service>
Vom System ausgenommen
- Typ des Dienstes im Vordergrund, der im Manifest unter
android:foregroundServiceType
systemExempted
- Berechtigung, die in Ihrem Manifest deklariert werden muss
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
- Konstante, die an
startForeground()
übergeben werden soll FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
- Laufzeitvoraussetzungen
- Keine
- Beschreibung
Reserviert für Systemanwendungen und bestimmte Systemintegrationen, um Dienste im Vordergrund weiterhin zu verwenden.
Damit dieser Typ verwendet werden kann, muss eine App mindestens eines der folgenden Kriterien erfüllen:
- Das Gerät befindet sich im Demomodus
- Die App ist ein Geräteeigentümer
- Die App ist ein Inhaber des Profilers
- Sicherheits-Apps mit der Rolle
ROLE_EMERGENCY
- Apps zur Geräteverwaltung
- Apps, die die Berechtigung
SCHEDULE_EXACT_ALARM
oderUSE_EXACT_ALARM
haben und Dienste im Vordergrund verwenden, um Wecker im Hintergrund fortzusetzen, einschließlich Weckern, die nur haptisches Feedback geben. VPN-Apps (konfiguriert über Einstellungen > Netzwerk und Internet > VPN)
Andernfalls löst die Deklaration dieses Typs eine
ForegroundServiceTypeNotAllowedException
aus.
Durchsetzung der Google Play-Richtlinien für die Verwendung von Typen von Diensten im Vordergrund
Wenn Ihre App auf Android 14 oder höher ausgerichtet ist, müssen Sie die Typen der Dienste im Vordergrund Ihrer App auf der Seite „App-Inhalte“ in der Play Console (Richtlinie > App-Inhalte) deklarieren. Weitere Informationen dazu, wie Sie die Typen Ihrer Dienste im Vordergrund in der Play Console deklarieren, finden Sie unter Anforderungen für Dienste im Vordergrund und Full-Screen Intents.