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:
cameraconnectedDevicedataSynchealthlocationmediaPlaybackmediaProjectionmicrophonephoneCallremoteMessagingshortServicespecialUsesystemExempted
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
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.
Çalışma zamanında ön plan hizmet türünü ekleme
Ön plan hizmetlerini başlatan uygulamalar için en iyi uygulama, ön plan hizmet türlerinin bitsel bir tam sayı değerini ilettiğiniz startForeground() işlevinin ServiceCompat sürümünü (androidx-core 1.12 ve sonraki sürümlerde kullanılabilir) kullanmaktır. Bir veya daha fazla tür değeri iletmeyi seçebilirsiniz.
Genellikle yalnızca belirli bir kullanım alanı için gereken türleri tanımlamanız gerekir. Bu sayede sistemin her ön plan hizmet türüne dair beklentilerini karşılayabilirsiniz. Bir ön plan hizmetinin birden fazla türle başlatıldığı durumlarda, ön plan hizmeti tüm türlerin platform yaptırım koşullarına uymalıdır.
ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)
Ön plan hizmet türü çağrıda belirtilmezse tür varsayılan olarak manifest'te tanımlanan değerlere ayarlanır. Manifest'te hizmet türünü belirtmediyseniz sistem MissingForegroundServiceTypeException hatası verir.
Ön plan hizmetini başlattıktan sonra yeni izinlere ihtiyacı olursa startForeground() işlevini tekrar çağırıp yeni hizmet türlerini eklemeniz gerekir. Örneğin, bir fitness uygulamasının her zaman location bilgisine ihtiyaç duyan ancak media izinlerine ihtiyaç duyabilecek ya da gerekmeyebilecek bir koşu takip aracı hizmeti çalıştırdığını varsayalım. Manifestte hem location hem de mediaPlayback öğelerini belirtmeniz gerekir. Bir kullanıcı koşuya başlar ve yalnızca konumunun izlenmesini isterse uygulamanız startForeground() işlevini çağırmalı ve yalnızca location hizmet türünü iletmelidir. Ardından, kullanıcı ses oynatmaya başlamak isterse startForeground() işlevini tekrar çağırın ve location|mediaPlayback parametresini iletin.
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
Belirli bir ön plan hizmet türünü kullanmak için manifest dosyanızda belirli bir izni beyan etmeniz, belirli çalışma zamanı koşullarını karşılamanız ve uygulamanızın, söz konusu tür için amaçlanan kullanım alanı gruplarından birini karşılaması gerekir. Aşağıdaki bölümlerde, beyan etmeniz gereken izin, çalışma zamanı ön koşulları ve her türün amaçlanan kullanım alanları açıklanmaktadır.
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
CAMERAruntime permissionNote: The
CAMERAruntime permission is subject to while-in-use restrictions. For this reason, you cannot create acameraforeground 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.
Bağlı cihaz
- Foreground service type to declare in manifest under
android:foregroundServiceTypeconnectedDevice- 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.
Veri senkronizasyonu
- Foreground service type to declare in manifest under
android:foregroundServiceTypedataSync- 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
- Manifest dosyasında aşağıdaki altında beyan edilecek ön plan hizmet türü
android:foregroundServiceTypehealth- Manifest dosyanızda beyan etme izni
FOREGROUND_SERVICE_HEALTHstartForeground()işlevine iletilen sabit değerFOREGROUND_SERVICE_TYPE_HEALTH- Çalışma zamanı ön koşulları
Aşağıdaki koşullardan en az biri doğru olmalıdır:
Manifest'inizde
HIGH_SAMPLING_RATE_SENSORSiznini beyan edin.Aşağıdaki çalışma zamanı izinlerinden en az birini talep edin ve alın:
- API düzeyi 35 ve önceki sürümlerde
BODY_SENSORS READ_HEART_RATEREAD_SKIN_TEMPERATUREREAD_OXYGEN_SATURATIONACTIVITY_RECOGNITION
- API düzeyi 35 ve önceki sürümlerde
Not:
BODY_SENSORSve sensör tabanlı OKU çalışma zamanında istenen izinleri, kullanım sırasındaki kısıtlamalara tabidir. Bu nedenle,BODY_SENSORS_BACKGROUND(API düzeyi 33 ila 35) veyaREAD_HEALTH_DATA_IN_BACKGROUND(API düzeyi 36 ve üzeri) izinleri verilmedikçe uygulamanız arka plandayken vücut sensörlerini kullanan birhealthö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
Fitness kategorisindeki uygulamaları (ör. egzersiz takipçileri) desteklemek için uzun süredir kullanılan tüm kullanım alanları.
Konum
- Manifest dosyasında aşağıdaki altında beyan edilecek ön plan hizmet türü
android:foregroundServiceTypelocation- Manifest dosyanızda beyan etme izni
FOREGROUND_SERVICE_LOCATIONstartForeground()işlevine iletilecek sabit değerFOREGROUND_SERVICE_TYPE_LOCATION- Çalışma zamanı ön koşulları
Kullanıcının konum hizmetlerini etkinleştirmiş olması ve uygulamaya aşağıdaki çalışma zamanında istenen izinlerden en az biri verilmiş olmalıdır:
Not: Kullanıcının konum hizmetlerini etkinleştirip etkinleştirmediğini ve çalışma zamanında izinlere erişim izni verip vermediğini kontrol etmek için
PermissionChecker#checkSelfPermission()Not: Çalışma zamanı konum izinleri, kullanım sırasındaki kısıtlamalara tabidir. Bu nedenle,
ACCESS_BACKGROUND_LOCATIONçalışma zamanında izin verilmedikçe uygulamanız arka plandaykenlocationö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
Navigasyon ve konum paylaşımı gibi konum erişimi gerektiren uzun süreli kullanım alanları.
- Alternatifler
Kullanıcı belirli konumlara ulaştığında uygulamanızın tetiklenmesi gerekiyorsa bunun yerine coğrafi çit API'sini kullanabilirsiniz.
Medya
- Manifest dosyasında aşağıdaki altında beyan edilecek ön plan hizmet türü
android:foregroundServiceTypemediaPlayback- Manifest dosyanızda beyan etme izni
FOREGROUND_SERVICE_MEDIA_PLAYBACKstartForeground()işlevine iletilecek sabit değerFOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK- Çalışma zamanı ön koşulları
- Yok
- Açıklama
- Ses veya video oynatmaya arka planda devam edin. Android TV'de Dijital Video Kaydı (DVR) işlevini destekleyin.
- Alternatifler
- Pencere içinde pencere modunda video gösteriyorsanız Pencere içinde pencere modunu kullanın.
Medya projeksiyonu
- Manifest dosyasında aşağıdaki altında beyan edilecek ön plan hizmet türü
android:foregroundServiceTypemediaProjection- Manifest dosyanızda beyan etme izni
FOREGROUND_SERVICE_MEDIA_PROJECTIONstartForeground()işlevine iletilecek sabit değerFOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION- Çalışma zamanı ön koşulları
Ön plan hizmetini başlatmadan önce
createScreenCaptureIntent()yöntemini çağırın. Bu işlem, kullanıcıya bir izin bildirimi gösterir. Hizmeti oluşturabilmeniz için kullanıcının izin vermesi gerekir.Ön plan hizmetini oluşturduktan sonra
MediaProjectionManager.getMediaProjection()işlevini çağırabilirsiniz.- Açıklama
MediaProjectionAPI'lerini kullanarak içeriği birincil olmayan ekrana veya harici cihaza yansıtın. Bu içeriğin yalnızca medya içeriği olması gerekmez.- Alternatifler
Medyayı başka bir cihaza aktarmak için Google Cast SDK'sını kullanın.
Mikrofon
- Foreground service type to declare in manifest under
android:foregroundServiceTypemicrophone- 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_AUDIOruntime permission.Note: The
RECORD_AUDIOruntime permission is subject to while-in-use restrictions. For this reason, you cannot create amicrophoneforeground 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.
Sesli arama
- Foreground service type to declare in manifest under
android:foregroundServiceTypephoneCall- 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_CALLSpermission in its manifest file.
- App has declared the
- App is the default dialer app through the
ROLE_DIALERrole.
- App is the default dialer app through the
- Description
Continue an ongoing call using the
ConnectionServiceAPIs.- Alternatives
If you need to make phone, video, or VoIP calls, consider using the
android.telecomlibrary.Consider using
CallScreeningServiceto screen calls.
Uzaktan mesajlaşma
- Manifest dosyasında aşağıdaki altında beyan edilecek ön plan hizmet türü
android:foregroundServiceTyperemoteMessaging- Manifest dosyanızda beyan etme izni
FOREGROUND_SERVICE_REMOTE_MESSAGINGstartForeground()işlevine iletilecek sabit değerFOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING- Çalışma zamanı ön koşulları
- Yok
- Açıklama
- Kısa mesajları bir cihazdan diğerine aktarın. Cihaz değiştiren kullanıcıların mesajlaşma görevlerine devam etmesine yardımcı olun.
Kısa servis
- Foreground service type to declare in manifest under
android:foregroundServiceTypeshortService- 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_SERVICEpermission. - A
shortServicecan 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
shortServiceat 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 callService.stopSelf()orService.stopForeground()before the timeout occurs. Otherwise, the newService.onTimeout()is called, giving apps a brief opportunity to callstopSelf()orstopForeground()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 mentionsFOREGROUND_SERVICE_TYPE_SHORT_SERVICE. For these reasons, it's considered best practice to implement theService.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 theService.onTimeout()callback yet.It's important to note that if the timeout of the
shortServiceis 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 theFOREGROUND_SERVICE_TYPE_SHORT_SERVICEparameter 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 aForegroundServiceStartNotAllowedException.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
shortServicetype and another foreground service type, the system ignores theshortServicetype declaration. However, the service must still adhere to the prerequisites of the other declared types. For more information, see the Foreground services documentation.
Özel kullanım
- Foreground service type to declare in manifest under
android:foregroundServiceTypespecialUse- 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_USEforeground 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 thespecialUsetype.<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:foregroundServiceTypesystemExempted- 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_EMERGENCYrole - Device Admin apps
- Apps holding
SCHEDULE_EXACT_ALARMorUSE_EXACT_ALARMpermission 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.