Ön plan hizmeti türleri zorunludur

Android 10, geliştiricilerin kullanıcılara yönelik ön plan hizmetlerini daha bilinçli bir şekilde tanımlamasına yardımcı olmak için <service> öğesinde android:foregroundServiceType özelliğini kullanıma sundu.

Android 14'ü hedefleyen uygulamalar, uygun ön plan hizmeti türlerini belirtmelidir. Android'in önceki sürümlerinde de olduğu gibi birden fazla tür birlikte kullanılabilir. Aşağıdaki listede, aralarından seçim yapabileceğiniz ön plan hizmeti türleri gösterilmektedir:

Uygulamanızdaki kullanım alanı bu türlerden hiçbiriyle ilişkilendirilmemişse mantığınızı WorkManager veya kullanıcı tarafından başlatılan veri aktarımı işlerini kullanacak şekilde taşımanızı öneririz.

health, remoteMessaging, shortService, specialUse ve systemExempted türleri, Android 14'te yenidir.

Aşağıdaki kod snippet'inde, manifest dosyasında ön plan hizmeti türü beyanı örneği verilmiştir:

<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>

Android 14'ü hedefleyen bir uygulama, manifest dosyasında belirli bir hizmet için türleri tanımlamazsa sistem, söz konusu hizmet için startForeground() çağrıldıktan sonra MissingForegroundServiceTypeException hatası oluşturur.

Ön plan hizmeti türlerini kullanmak için yeni izin bildir

如果以 Android 14 为目标平台的应用使用前台服务,则必须根据前台服务类型声明 Android 14 中引入的特定权限。这些权限显示在本页每种前台服务类型的预期用例和强制执行部分中标记为“您必须在清单文件中声明的权限”的部分。

所有这些权限都定义为一般权限,并默认授予。用户无法撤消这些权限。

Çalışma zamanında ön plan hizmet türünü ekleme

对于启动前台服务的应用,最佳实践是使用 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。

Sistem çalışma zamanı kontrolleri

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.

Her ön plan hizmet türü için amaçlanan kullanım alanları ve yaptırım

为了使用给定的前台服务类型,您必须在清单文件中声明特定权限,必须满足特定的运行时要求,并且应用必须满足该类型的其中一组预期用例。以下部分介绍了您必须声明的权限、运行时前提条件以及每种类型的预期用例。

Kamera

要在 android:foregroundServiceType 下在清单中声明的前台服务类型
camera
在清单中声明的权限
FOREGROUND_SERVICE_CAMERA
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_CAMERA
运行时前提条件

请求并获得 CAMERA 运行时权限

注意:CAMERA 运行时权限受使用时限制的约束。因此,除少数例外情况外,您无法在应用在后台运行时创建 camera 前台服务。如需了解详情,请参阅与启动需要“使用时”权限的前台服务相关的限制。

说明

继续在后台访问相机,例如支持多任务的视频聊天应用。

Bağlı cihaz

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:

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.

Veri senkronizasyonu

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.

Sağlık

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
health
在清单中声明的权限
FOREGROUND_SERVICE_HEALTH
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_HEALTH
运行时前提条件

必须至少满足以下其中一个条件:

注意:BODY_SENSORS 和基于传感器的读取运行时权限受“在使用时”限制。因此,除非您已获得 BODY_SENSORS_BACKGROUND(API 级别 33 到 35)或 READ_HEALTH_DATA_IN_BACKGROUND(API 级别 36 及更高级别)权限,否则您无法创建在应用处于后台运行时使用身体传感器的 health 前台服务。如需了解详情,请参阅与启动需要使用时权限的前台服务相关的限制。

说明

为健身类别的应用(例如锻炼追踪器)提供支持的所有长时间运行的用例。

Konum

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
location
在清单中声明的权限
FOREGROUND_SERVICE_LOCATION
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_LOCATION
运行时前提条件

用户必须已启用位置信息服务,并且应用必须至少获得以下一项运行时权限:

注意:如需检查用户是否已启用位置信息服务以及是否已授予对运行时权限的访问权限,请使用 PermissionChecker#checkSelfPermission()

注意:位置信息运行时权限受“使用期间”限制。因此,除非您已获得 ACCESS_BACKGROUND_LOCATION 运行时权限,否则无法在应用在后台运行时创建 location 前台服务。如需了解详情,请参阅与启动需要“使用时”权限的前台服务相关的限制。

说明

需要位置信息使用权的长时间运行的用例,例如导航和位置信息分享。

替代方案

如果您的应用需要在用户到达特定位置时触发,请考虑改用 Geofence API。

Medya

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
mediaPlayback
在清单中声明的权限
FOREGROUND_SERVICE_MEDIA_PLAYBACK
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
运行时前提条件
无
说明
在后台继续播放音频或视频。在 Android TV 上支持数字视频录制 (DVR) 功能。
替代方案
如果您要显示画中画视频,请使用画中画模式。

Medya projeksiyonu

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
mediaProjection
在清单中声明的权限
FOREGROUND_SERVICE_MEDIA_PROJECTION
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
运行时前提条件

在启动前台服务之前调用 createScreenCaptureIntent() 方法。这样做会向用户显示权限通知;用户必须先授予权限,您才能创建服务。

创建前台服务后,您可以调用 MediaProjectionManager.getMediaProjection()。

说明

使用 MediaProjection API 将内容投影到非主要显示屏或外部设备。这些内容不必全都为媒体内容。

替代方案

如需将媒体流式传输到其他设备,请使用 Google Cast SDK。

Mikrofon

Manifest dosyasında aşağıdaki altında beyan edilecek ön plan hizmet türü
android:foregroundServiceType
microphone
Manifest dosyanızda beyan etme izni
FOREGROUND_SERVICE_MICROPHONE
startForeground() işlevine iletilecek sabit değer
FOREGROUND_SERVICE_TYPE_MICROPHONE
Çalışma zamanı ön koşulları

RECORD_AUDIO çalışma zamanı iznini isteyin ve izni alın.

Not: RECORD_AUDIO çalışma zamanı izni, kullanım sırasındaki kısıtlamalara tabidir. Bu nedenle, birkaç istisna dışında uygulamanız arka plandayken microphone ön plan hizmeti oluşturamazsınız. Daha fazla bilgi için Kullanımdayken izin gerektiren ön plan hizmetlerini başlatmayla ilgili kısıtlamalar başlıklı makaleyi inceleyin.

Açıklama

Ses kaydediciler veya iletişim uygulamaları gibi mikrofon kayıtlarına arka planda devam edin.

Sesli arama

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 is the default dialer app through the ROLE_DIALER role.
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.

Uzaktan mesajlaşma

要在清单中的以下位置声明的前台服务类型
android:foregroundServiceType
remoteMessaging
在清单中声明的权限
FOREGROUND_SERVICE_REMOTE_MESSAGING
要传递给 startForeground() 的常量
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
运行时前提条件
无
说明
将短信从一台设备转移到另一台设备。在用户切换设备时,帮助确保用户消息任务的连续性。

Kısa servis

Manifest dosyasında aşağıdaki altında beyan edilecek ön plan hizmet türü
android:foregroundServiceType
shortService
Manifest dosyanızda beyan etme izni
Yok
startForeground() işlevine iletilecek sabit değer
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
Çalışma zamanı ön koşulları
Yok
Açıklama

Kesintiye uğratılamayan veya ertelenemeyecek kritik işleri hızlıca tamamlayın.

Bu türün bazı benzersiz özellikleri vardır:

  • Yalnızca kısa bir süre (yaklaşık 3 dakika) çalışabilir.
  • Yapışkan ön plan hizmetleri desteklenmez.
  • Diğer ön plan hizmetleri başlatılamaz.
  • Türe özgü izin gerektirmez ancak FOREGROUND_SERVICE iznini gerektirir.
  • shortService yalnızca uygulama şu anda yeni bir ön plan hizmeti başlatmaya uygunsa başka bir hizmet türüne geçirilebilir.
  • Ön plan hizmetleri, türlerini istedikleri zaman shortService olarak değiştirebilir. Bu durumda zaman aşımı süresi başlar.

shortService için zaman aşımı, Service.startForeground() çağrıldığı andan itibaren başlar. Uygulamanın, zaman aşımı gerçekleşmeden önce Service.stopSelf() veya Service.stopForeground() çağrısını yapması beklenir. Aksi takdirde yeni Service.onTimeout() çağrılır ve uygulamalara, hizmetlerini durdurmak için stopSelf() veya stopForeground()'yi aramak üzere kısa bir fırsat verilir.

Service.onTimeout() çağrıldıktan kısa bir süre sonra uygulama önbelleğe alınmış bir duruma girer ve kullanıcı uygulamayla etkin bir şekilde etkileşimde bulunmadığı sürece artık ön planda olduğu kabul edilmez. Uygulama önbelleğe alındıktan ve hizmet durdurulmadıktan kısa bir süre sonra ANR alır. ANR mesajında FOREGROUND_SERVICE_TYPE_SHORT_SERVICE geçiyor. Bu nedenlerden dolayı, Service.onTimeout() geri çağırma işlevini uygulamak en iyi uygulama olarak kabul edilir.

Service.onTimeout() geri arama işlevi Android 13 ve önceki sürümlerde mevcut değildir. Aynı hizmet bu tür cihazlarda çalışıyorsa zaman aşımı veya ANR almaz. İşleme görevini tamamlar tamamlamaz, henüz Service.onTimeout() geri çağırma almamış olsa bile hizmetinizin durmasını sağlayın.

shortService zaman aşımına uyulmaması durumunda, geçerli başka ön plan hizmetleri veya çalışan başka uygulama yaşam döngüsü süreçleri olsa bile uygulamanın ANR'ye neden olacağını unutmayın.

Bir uygulama kullanıcı tarafından görülebilirse veya ön plan hizmetlerinin arka plandan başlatılmasına izin veren istisnalardan birini karşılıyorsa Service.StartForeground() işlevi FOREGROUND_SERVICE_TYPE_SHORT_SERVICE parametresiyle tekrar çağrılırsa zaman aşımı 3 dakika daha uzatılır. Uygulama kullanıcı tarafından görülmüyorsa ve istisnalardan birini karşılamıyorsa türünden bağımsız olarak başka bir ön plan hizmeti başlatma girişimi ForegroundServiceStartNotAllowedException'a neden olur.

Bir kullanıcı uygulamanız için pil optimizasyonunu devre dışı bırakırsa uygulamanız shortService FGS zaman aşımından etkilenmeye devam eder.

shortService türünü ve başka bir ön plan hizmet türünü içeren bir ön plan hizmeti başlatırsanız sistem, shortService türü bildirimini yoksayar. Ancak hizmet, beyan edilen diğer türlerin ön koşullarına uymaya devam etmelidir. Daha fazla bilgi için Ön plan hizmetleri belgelerine bakın.

Özel kullanım

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 the specialUse 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>

Sistem muaf

Foreground service type to declare in manifest under
android:foregroundServiceType
systemExempted
Permission to declare in your manifest
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
Runtime prerequisites
None
Description

Reserved for system applications and specific system integrations, to continue to use foreground services.

To use this type, an app must meet at least one of the following criteria:

  • Device is in demo mode state
  • App is a Device Owner
  • App is a Profiler Owner
  • Safety Apps that have the ROLE_EMERGENCY role
  • Device Admin apps
  • Apps holding SCHEDULE_EXACT_ALARM or USE_EXACT_ALARM permission and are using Foreground Service to continue alarms in the background, including haptics-only alarms.
  • VPN apps (configured using Settings > Network & Internet > VPN)

    Otherwise, declaring this type causes the system to throw a ForegroundServiceTypeNotAllowedException.

Ön plan hizmet türlerinin kullanımıyla ilgili Google Play politika yaptırımı

Uygulamanız Android 14 veya sonraki sürümleri hedefliyorsa uygulamanızın ön plan hizmet türlerini Play Console'un uygulama içeriği sayfasında (Politika > Uygulama içeriği) belirtmeniz gerekir. Play Console'da ön plan hizmet türlerinizi nasıl beyan edeceğiniz hakkında daha fazla bilgi için Ön plan hizmetini ve tam ekran intent şartlarını anlama başlıklı makaleyi inceleyin.