Jenis layanan latar depan wajib diisi

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:

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.

Mendeklarasikan izin baru untuk menggunakan jenis layanan latar depan

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.

Menyertakan jenis layanan latar depan saat runtime

Praktik terbaik untuk aplikasi yang memulai layanan latar depan adalah menggunakan versi ServiceCompat dari startForeground() (tersedia di androidx-core 1.12 dan yang lebih tinggi) tempat Anda meneruskan bilangan bulat dari jenis layanan latar depan bitwise. Anda dapat memilih untuk meneruskan satu atau beberapa nilai jenis.

Biasanya, Anda hanya boleh mendeklarasikan jenis yang diperlukan untuk kasus penggunaan tertentu. Hal ini memudahkan Anda memenuhi ekspektasi sistem untuk setiap jenis layanan latar depan. Jika layanan latar depan dimulai dengan beberapa jenis, layanan latar depan harus mematuhi persyaratan penerapan platform dari semua jenis.

ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)

Jika jenis layanan latar depan tidak ditentukan dalam panggilan, jenis layanan yang digunakan dalam manifes akan ditetapkan secara default. Jika Anda tidak menentukan jenis layanan dalam manifes, sistem akan menampilkan MissingForegroundServiceTypeException.

Jika layanan latar depan memerlukan izin baru setelah diluncurkan, Anda harus memanggil startForeground() lagi dan menambahkan jenis layanan baru. Misalnya, aplikasi kebugaran menjalankan layanan pelacak lari yang selalu memerlukan informasi location, tetapi mungkin atau mungkin tidak memerlukan izin media. Anda harus mendeklarasikan location dan mediaPlayback dalam manifes. Jika pengguna mulai berlari dan hanya ingin lokasi mereka dilacak, aplikasi Anda harus memanggil startForeground() dan meneruskan jenis layanan location saja. Kemudian, jika pengguna ingin mulai memutar audio, panggil startForeground() lagi dan teruskan location|mediaPlayback.

Pemeriksaan runtime sistem

Sistem akan memeriksa penggunaan jenis layanan latar depan yang tepat dan mengonfirmasi bahwa aplikasi telah meminta izin runtime yang tepat atau menggunakan API yang diperlukan. Misalnya, sistem mengharapkan aplikasi yang menggunakan jenis layanan latar depan FOREGROUND_SERVICE_TYPE_LOCATION untuk meminta ACCESS_COARSE_LOCATION atau ACCESS_FINE_LOCATION.

Artinya, aplikasi harus mengikuti urutan operasi yang sangat spesifik saat meminta izin dari pengguna dan memulai layanan latar depan. Izin harus diminta dan diberikan sebelum aplikasi mencoba memanggil startForeground(). Aplikasi yang meminta izin yang sesuai setelah layanan latar depan dimulai harus mengubah urutan operasi ini dan meminta izin sebelum memulai layanan latar depan.

Detail penerapan platform akan muncul di bagian berlabel "persyaratan runtime" di bagian kasus penggunaan dan penerapan yang diinginkan untuk setiap jenis layanan latar depan di halaman ini.

Kasus penggunaan dan penerapan yang ditargetkan untuk setiap jenis layanan latar depan

Untuk menggunakan jenis layanan latar depan tertentu, Anda harus mendeklarasikan izin tertentu dalam file manifes, Anda harus memenuhi persyaratan runtime tertentu, dan aplikasi Anda harus memenuhi salah satu dari kumpulan kasus penggunaan yang dimaksudkan untuk jenis tersebut. Bagian berikut menjelaskan izin yang harus Anda deklarasikan, prasyarat runtime, dan kasus penggunaan yang dimaksudkan untuk setiap jenis.

Kamera

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 permission

Note: The CAMERA runtime permission is subject to while-in-use restrictions. For this reason, you cannot create a camera 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.

Perangkat yang terhubung

Jenis layanan latar depan yang akan dideklarasikan dalam manifes di bagian
android:foregroundServiceType
connectedDevice
Izin untuk dideklarasikan dalam manifes
FOREGROUND_SERVICE_CONNECTED_DEVICE
Konstanta yang akan diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
Prasyarat runtime

Setidaknya salah satu syarat berikut harus terpenuhi:

Deskripsi

Interaksi dengan perangkat eksternal yang memerlukan Bluetooth, NFC, IR, USB, atau koneksi jaringan.

Alternatif

Jika aplikasi Anda perlu melakukan transfer data berkelanjutan ke perangkat eksternal, pertimbangkan untuk menggunakan pengelola perangkat pendamping. Gunakan API kehadiran perangkat pendamping untuk membantu aplikasi Anda tetap berjalan saat perangkat pendamping berada dalam jangkauan.

Jika aplikasi Anda perlu memindai perangkat Bluetooth, sebaiknya gunakan Bluetooth scan API.

Sinkronisasi data

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.

Kesehatan

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:

Note: The BODY_SENSORS and sensor-based READ runtime permissions are subject to while-in-use restrictions. For this reason, you cannot create a health foreground service that uses body sensors while your app is in the background unless you've been granted the BODY_SENSORS_BACKGROUND (API level 33 to 35) or READ_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.

Lokasi

Jenis layanan latar depan yang akan dideklarasikan dalam manifes di bagian
android:foregroundServiceType
location
Izin untuk dideklarasikan dalam manifes
FOREGROUND_SERVICE_LOCATION
Konstanta yang akan diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_LOCATION
Prasyarat runtime

Pengguna harus telah mengaktifkan layanan lokasi dan aplikasi harus diberi setidaknya salah satu izin runtime berikut:

Catatan: Untuk memeriksa apakah pengguna telah mengaktifkan layanan lokasi serta memberikan akses ke izin runtime, gunakan PermissionChecker#checkSelfPermission()

Catatan: Izin runtime lokasi tunduk pada pembatasan saat digunakan. Oleh karena itu, Anda tidak dapat membuat layanan latar depan location saat aplikasi berada di latar belakang, kecuali jika Anda telah diberi izin runtime ACCESS_BACKGROUND_LOCATION. Untuk mengetahui informasi selengkapnya, lihat Batasan untuk memulai layanan latar depan yang memerlukan izin saat digunakan.

Deskripsi

Kasus penggunaan jangka panjang yang memerlukan akses lokasi, seperti navigasi dan berbagi lokasi.

Alternatif

Jika aplikasi Anda perlu dipicu saat pengguna mencapai lokasi tertentu, pertimbangkan untuk menggunakan geofence API.

Media

Jenis layanan latar depan yang akan dideklarasikan dalam manifes di bagian
android:foregroundServiceType
mediaPlayback
Izin untuk dideklarasikan dalam manifes
FOREGROUND_SERVICE_MEDIA_PLAYBACK
Konstanta yang akan diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
Prasyarat runtime
Tidak ada
Deskripsi
Melanjutkan pemutaran audio atau video dari latar belakang. Mendukung fungsi Perekaman Video Digital (DVR) di Android TV.
Alternatif
Jika Anda menampilkan video picture-in-picture, gunakan mode Picture-in-Picture.

Proyeksi media

Jenis layanan latar depan yang akan dideklarasikan dalam manifes di bagian
android:foregroundServiceType
mediaProjection
Izin untuk dideklarasikan dalam manifes
FOREGROUND_SERVICE_MEDIA_PROJECTION
Konstanta yang akan diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
Prasyarat runtime

Panggil metode createScreenCaptureIntent() sebelum memulai layanan latar depan. Tindakan ini akan menampilkan notifikasi izin kepada pengguna; pengguna harus memberikan izin sebelum Anda dapat membuat layanan.

Setelah membuat layanan latar depan, Anda dapat memanggil MediaProjectionManager.getMediaProjection().

Deskripsi

Proyeksikan konten ke layar non-utama atau perangkat eksternal menggunakan MediaProjection API. Konten ini tidak harus berupa konten media saja.

Alternatif

Untuk melakukan streaming media ke perangkat lain, gunakan 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 a microphone 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.

Panggilan telepon

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

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

  • 应用是通过 ROLE_DIALER 角色的默认拨号器应用。
说明

使用 ConnectionService API 继续当前通话。

替代方案

如果您需要拨打电话、视频通话或 VoIP 通话,不妨考虑使用 android.telecom 库。

考虑使用 CallScreeningService 来过滤来电。

Pengiriman pesan jarak jauh

Jenis layanan latar depan yang akan dideklarasikan dalam manifes di bagian
android:foregroundServiceType
remoteMessaging
Izin untuk dideklarasikan dalam manifes
FOREGROUND_SERVICE_REMOTE_MESSAGING
Konstanta yang akan diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
Prasyarat runtime
Tidak ada
Deskripsi
Mentransfer pesan teks dari satu perangkat ke perangkat lainnya. Membantu kontinuitas tugas fitur pesan pengguna saat mereka beralih perangkat.

Layanan singkat

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

Quickly finish critical work that cannot be interrupted or postponed.

This type has some unique characteristics:

  • Can only run for a short period of time (about 3 minutes).
  • No support for sticky foreground services.
  • Cannot start other foreground services.
  • Doesn't require a type-specific permission, though it still requires the FOREGROUND_SERVICE permission.
  • A shortService can only change to another service type if the app is currently eligible to start a new foreground service.
  • A foreground service can change its type to shortService at any time, at which point the timeout period begins.

The timeout for shortService begins from the moment that Service.startForeground() is called. The app is expected to call Service.stopSelf() or Service.stopForeground() before the timeout occurs. Otherwise, the new Service.onTimeout() is called, giving apps a brief opportunity to call stopSelf() or stopForeground() to stop their service.

A short time after Service.onTimeout() is called, the app enters a cached state and is no longer considered to be in the foreground, unless the user is actively interacting with the app. A short time after the app is cached and the service has not stopped, the app receives an ANR. The ANR message mentions FOREGROUND_SERVICE_TYPE_SHORT_SERVICE. For these reasons, it's considered best practice to implement the Service.onTimeout() callback.

The Service.onTimeout() callback doesn't exist on Android 13 and lower. If the same service runs on such devices, it doesn't receive a timeout, nor does it ANR. Make sure that your service stops as soon as it finishes the processing task, even if it hasn't received the Service.onTimeout() callback yet.

It's important to note that if the timeout of the shortService is not respected, the app will ANR even if it has other valid foreground services or other app lifecycle processes running.

If an app is visible to the user or satisfies one of the exemptions that allow foreground services to be started from the background, calling Service.StartForeground() again with the FOREGROUND_SERVICE_TYPE_SHORT_SERVICE parameter extends the timeout by another 3 minutes. If the app isn't visible to the user and doesn't satisfy one of the exemptions, any attempt to start another foreground service, regardless of type, causes a ForegroundServiceStartNotAllowedException.

If a user disables battery optimization for your app, it's still affected by the timeout of shortService FGS.

If you start a foreground service that includes the shortService type and another foreground service type, the system ignores the shortService type declaration. However, the service must still adhere to the prerequisites of the other declared types. For more information, see the Foreground services documentation.

Penggunaan khusus

Jenis layanan latar depan yang akan dinyatakan dalam manifes di
android:foregroundServiceType
specialUse
Izin yang akan dideklarasikan dalam manifes
FOREGROUND_SERVICE_SPECIAL_USE
Konstanta yang akan diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
Prasyarat runtime
Tidak ada
Deskripsi

Mencakup semua kasus penggunaan layanan latar depan yang valid dan tidak tercakup dalam jenis layanan latar depan lainnya.

Selain mendeklarasikan jenis layanan latar depan FOREGROUND_SERVICE_TYPE_SPECIAL_USE, developer juga harus mendeklarasikan kasus penggunaan dalam manifes. Untuk melakukannya, mereka menentukan elemen <property> dalam elemen <service>. Nilai ini dan kasus penggunaan yang sesuai akan ditinjau saat Anda mengirimkan aplikasi di Konsol Google Play. Penggunaan kasus yang Anda berikan menggunakan format bebas, dan Anda harus memastikan agar peninjau dapat mengetahui alasan Anda perlu menggunakan specialUse .

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

Jenis layanan latar depan yang akan dideklarasikan dalam manifes di bagian
android:foregroundServiceType
systemExempted
Izin untuk dideklarasikan dalam manifes
FOREGROUND_SERVICE_SYSTEM_EXEMPTED
Konstanta yang akan diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED
Prasyarat runtime
Tidak ada
Deskripsi

Ditujukan bagi aplikasi sistem dan integrasi sistem tertentu, untuk terus menggunakan layanan latar depan.

Untuk menggunakan jenis ini, aplikasi harus memenuhi setidaknya salah satu kriteria berikut:

  • Perangkat dalam status mode demo
  • Aplikasi adalah Pemilik Perangkat
  • Aplikasi adalah Pemilik Profiler
  • Aplikasi Keselamatan yang memiliki peran ROLE_EMERGENCY
  • Aplikasi Admin Perangkat
  • Aplikasi yang memiliki izin SCHEDULE_EXACT_ALARM atau USE_EXACT_ALARM dan menggunakan Layanan Latar Depan untuk melanjutkan alarm di latar belakang, termasuk alarm khusus haptic.
  • Aplikasi VPN (dikonfigurasi menggunakan Setelan > Jaringan & Internet > VPN)

    Jika tidak, mendeklarasikan jenis ini akan menyebabkan sistem menampilkan ForegroundServiceTypeNotAllowedException.

Penegakan kebijakan Google Play untuk menggunakan jenis layanan latar depan

Jika aplikasi menargetkan Android 14 atau yang lebih baru, Anda harus menyatakan jenis layanan latar depan aplikasi di halaman konten aplikasi Konsol Play (Kebijakan > Konten aplikasi). Untuk informasi selengkapnya tentang cara mendeklarasikan jenis layanan latar depan di Konsol Play, lihat Memahami persyaratan layanan latar depan dan intent layar penuh.