Jenis layanan latar depan wajib diisi

Untuk mendorong agar developer berusaha lebih keras menentukan layanan latar depan yang ditampilkan kepada pengguna, Android 10 memperkenalkan atribut android:foregroundServiceType dalam elemen <service>.

Jika menargetkan Android 14, aplikasi Anda harus menentukan jenis layanan latar depan yang sesuai. Seperti pada versi Android sebelumnya, beberapa jenis dapat digabungkan. Daftar ini menunjukkan jenis layanan latar depan yang dapat dipilih:

Jika kasus penggunaan di aplikasi Anda tidak terkait dengan salah satu jenis ini, sebaiknya migrasikan logika untuk menggunakan WorkManager atau tugas transfer data yang dimulai pengguna

Jenis health, remoteMessaging, shortService, specialUse, dan systemExempted masih baru di Android 14.

Cuplikan kode berikut menyediakan contoh deklarasi jenis layanan latar depan dalam manifes:

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

Jika aplikasi yang menargetkan Android 14 tidak menentukan jenis untuk layanan tertentu dalam manifes, sistem akan memunculkan MissingForegroundServiceTypeException saat memanggil startForeground() untuk layanan itu.

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 startForeground() (tersedia di androidx-core 1.12 dan yang lebih baru) 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 ini akan ditetapkan secara default ke nilai yang ditentukan dalam manifes. 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 pemantau lari yang selalu memerlukan informasi location, tetapi mungkin memerlukan atau mungkin tidak memerlukan izin media. Anda perlu mendeklarasikan location dan mediaPlayback dalam manifes. Jika pengguna memulai run dan hanya ingin melacak lokasinya, aplikasi Anda harus memanggil startForeground() dan hanya meneruskan jenis layanan location. 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 untuk dideklarasikan dalam manifes di
android:foregroundServiceType
connectedDevice
Izin untuk dideklarasikan dalam manifes Anda
FOREGROUND_SERVICE_CONNECTED_DEVICE
Konstanta untuk 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, sebaiknya gunakan 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

Jenis layanan latar depan untuk dideklarasikan dalam manifes di
android:foregroundServiceType
dataSync
Izin untuk dideklarasikan dalam manifes Anda
FOREGROUND_SERVICE_DATA_SYNC
Konstanta untuk diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_DATA_SYNC
Prasyarat runtime
Tidak ada
Deskripsi

Operasi transfer data, seperti berikut:

  • Upload atau download data
  • Operasi pencadangan dan pemulihan
  • Operasi impor atau ekspor
  • Mengambil data
  • Pemrosesan file lokal
  • Mentransfer data antara perangkat dan cloud melalui jaringan
Alternatif

Buat tugas transfer data yang dimulai pengguna untuk memungkinkan pengguna memulai tugas upload atau download data yang berjalan lama.

Gunakan API pengelola download untuk mendownload data dari URI.

Gunakan BackupManager untuk mencadangkan atau memulihkan data.

Untuk kasus penggunaan lainnya, pertimbangkan WorkManager.

Kesehatan

Jenis layanan latar depan untuk dinyatakan dalam manifes di bawah
android:foregroundServiceType
health
Izin untuk dideklarasikan dalam manifes Anda
FOREGROUND_SERVICE_HEALTH
Konstanta untuk diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_HEALTH
Prasyarat runtime

Setidaknya salah satu syarat berikut harus terpenuhi:

Catatan: Izin runtime BODY_SENSORS tunduk pada pembatasan saat digunakan. Karena alasan ini, Anda tidak dapat membuat layanan latar depan health yang menggunakan sensor tubuh saat aplikasi berada di latar belakang, dengan beberapa pengecualian. Untuk informasi selengkapnya, lihat Pembatasan memulai layanan latar depan yang memerlukan izin saat digunakan.

Deskripsi

Semua kasus penggunaan yang berjalan lama untuk mendukung aplikasi dalam kategori kebugaran seperti pelacak latihan.

Lokasi

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

Minta dan berikan minimal salah satu izin runtime berikut:

Catatan: Izin runtime lokasi tunduk pada pembatasan saat digunakan. Karena alasan ini, Anda tidak dapat membuat layanan latar depan location saat aplikasi Anda berada di latar belakang, dengan beberapa pengecualian. Untuk informasi selengkapnya, lihat Pembatasan 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, sebaiknya gunakan API pembatasan wilayah.

Media

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.

Proyeksi media

Jenis layanan latar depan untuk dideklarasikan dalam manifes di
android:foregroundServiceType
mediaProjection
Izin untuk dideklarasikan dalam manifes Anda
FOREGROUND_SERVICE_MEDIA_PROJECTION
Konstanta untuk 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

Project 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 SDK Google Cast.

Mikrofon

Jenis layanan latar depan untuk dideklarasikan dalam manifes di
android:foregroundServiceType
microphone
Izin untuk dideklarasikan dalam manifes Anda
FOREGROUND_SERVICE_MICROPHONE
Konstanta untuk diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_MICROPHONE
Prasyarat runtime

Minta dan diberi izin runtime RECORD_AUDIO.

Catatan: Izin runtime RECORD_AUDIO tunduk pada pembatasan saat digunakan. Karena alasan ini, Anda tidak dapat membuat layanan latar depan microphone saat aplikasi Anda berada di latar belakang, dengan beberapa pengecualian. Untuk informasi selengkapnya, lihat Pembatasan memulai layanan latar depan yang memerlukan izin saat digunakan.

Deskripsi

Lanjutkan perekaman mikrofon dari latar belakang, seperti perekam suara atau aplikasi komunikasi.

Panggilan telepon

Jenis layanan latar depan untuk dideklarasikan dalam manifes di
android:foregroundServiceType
phoneCall
Izin untuk dideklarasikan dalam manifes Anda
FOREGROUND_SERVICE_PHONE_CALL
Konstanta untuk diteruskan ke startForeground()
FOREGROUND_SERVICE_TYPE_PHONE_CALL
Prasyarat runtime

Setidaknya salah satu syarat berikut harus terpenuhi:

  • Aplikasi adalah aplikasi telepon default melalui peran ROLE_DIALER.
Deskripsi

Lanjutkan panggilan yang sedang berlangsung menggunakan ConnectionService API.

Alternatif

Jika Anda perlu melakukan panggilan telepon, video, atau VoIP, sebaiknya gunakan library android.telecom.

Sebaiknya gunakan CallScreeningService untuk menyaring panggilan.

Pengiriman pesan jarak jauh

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.

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

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 dikecualikan

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:

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 mengetahui informasi selengkapnya tentang cara mendeklarasikan jenis layanan latar depan di Konsol Play, lihat Memahami layanan latar depan dan persyaratan intent layar penuh.