Typy usług działających na pierwszym planie

Począwszy od Androida 14 (interfejs API 34) musisz zadeklarować odpowiedni typ usługi dla każdej usługi na pierwszym planie. Oznacza to, że musisz zadeklarować typ usługi w pliku manifestu aplikacji i poprosić o odpowiednie uprawnienie usługi na pierwszym planie dla tego typu (oprócz uprawnienia FOREGROUND_SERVICE). Ponadto w zależności od typu usługi na pierwszym planie przed jej uruchomieniem może być konieczne poproszenie o uprawnienia dotyczące czasu wykonywania.

.

Aparat

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

Description

Continue to access the camera from the background, such as video chat apps that allow for multitasking.

Połączone urządzenie

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.

Synchronizowanie danych

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.

Stan

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:

Description

Any long-running use cases to support apps in the fitness category such as exercise trackers.

Lokalizacja

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:

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.

Multimedia

Typ usługi na pierwszym planie do zadeklarowania w pliku manifestu w sekcji
android:foregroundServiceType
mediaPlayback
Uprawnienia do zadeklarowania w pliku manifestu
FOREGROUND_SERVICE_MEDIA_PLAYBACK
Stała wartość przekazywana do funkcji startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
Wymagania wstępne środowiska wykonawczego
Brak
Opis

Dotyczy to ciągłego odtwarzania dźwięku lub wideo w tle. Obsługa funkcji cyfrowego nagrywania wideo (DVR) na Androidzie TV.

Alternatywy

Jeśli wyświetlasz film w trybie obrazu w obrazie, użyj trybu obrazu w obrazie.

Przetwarzane materiały

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

Service for performing time-consuming operations on media assets, like converting media to different formats. The system allows this service a limited time to run; under normal circumstances, this time limit would be 6 hours out of every 24. (This limit is shared by all of an app's mediaProcessing foreground services.)

Your app should manually stop the media processing service in the following scenario:

If the timeout period is reached, the system calls the service's Service.onTimeout(int, int) method. At this time, the service has a few seconds to call Service.stopSelf(). If the service does not call Service.stopSelf(), an ANR will occur with this error message: "A foreground service of <fgs_type> did not stop within its timeout: <component_name>".

Note: Service.onTimeout(int, int) is not available on Android 14 or lower. On devices running those versions, if a media processing service reaches the timeout period, the system immediately caches the app. For this reason, your app shouldn't wait to get a timeout notification. Instead, it should terminate the foreground service or change it to a background service as soon as appropriate.

Wyświetlanie multimediów

Typ usługi na pierwszym planie do zadeklarowania w pliku manifestu w sekcji
android:foregroundServiceType
mediaProjection
Uprawnienia do zadeklarowania w pliku manifestu
FOREGROUND_SERVICE_MEDIA_PROJECTION
Stała wartość przekazywana do funkcji startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
Wymagania wstępne środowiska wykonawczego

Przed uruchomieniem usługi na pierwszym planie wywołaj metodę createScreenCaptureIntent(). W ten sposób wyświetli się powiadomienie o uprawnieniach. Użytkownik musi przyznać uprawnienia, zanim będzie można utworzyć usługę.

Po utworzeniu usługi na pierwszym planie możesz wywołać funkcję MediaProjectionManager.getMediaProjection().

Opis

Wyświetlanie treści na wyświetlaczu innym niż główny lub urządzeniu zewnętrznym przy użyciu interfejsów MediaProjection API. Te treści nie muszą być wyłącznie treściami multimedialnymi.

Alternatywy

Aby przesyłać strumieniowo multimedia na inne urządzenie, użyj pakietu SDK Google Cast.

mikrofon

Typ usługi na pierwszym planie do zadeklarowania w pliku manifestu w sekcji
android:foregroundServiceType
microphone
Uprawnienia do zadeklarowania w pliku manifestu
FOREGROUND_SERVICE_MICROPHONE
Stała wartość przekazywana do funkcji startForeground()
FOREGROUND_SERVICE_TYPE_MICROPHONE
Wymagania wstępne środowiska wykonawczego

Poproś o przyznanie uprawnień czasu działania RECORD_AUDIO.

.
Opis

Kontynuowanie rejestrowania dźwięku przez mikrofon w tle, np. w nagrywarkach głosowych lub aplikacjach do komunikacji.

Rozmowa telefoniczna

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.

Zdalne przesyłanie wiadomości

Typ usługi na pierwszym planie do zadeklarowania w pliku manifestu w domenie
android:foregroundServiceType
remoteMessaging
Uprawnienia do zadeklarowania w pliku manifestu
FOREGROUND_SERVICE_REMOTE_MESSAGING
Stała do przekazywania do: startForeground()
FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
Wymagania wstępne środowiska wykonawczego
Brak
Opis
Przenoszenie SMS-ów z jednego urządzenia na drugie. Zapewnia ciągłość zadań związanych z wiadomościami przy przełączaniu się na inne urządzenie.

Krótkie usługi

Typ usługi na pierwszym planie do zadeklarowania w pliku manifestu w domenie
android:foregroundServiceType
shortService
Uprawnienia do zadeklarowania w pliku manifestu
Brak
Stała do przekazywania do: startForeground()
FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
Wymagania wstępne środowiska wykonawczego
Brak
Opis

Szybko kończ najważniejsze zadania, których nie można przerwać ani odłożyć na później.

Ten typ ma kilka wyjątkowych cech:

  • Może być aktywna tylko przez krótki czas (około 3 minuty).
  • Brak obsługi usług przyklejonych na pierwszym planie.
  • Nie można uruchomić innych usług działających na pierwszym planie.
  • Nie wymaga uprawnień dotyczących konkretnego typu, ale nadal wymaga uprawnienia FOREGROUND_SERVICE.
  • Usługa shortService może się zmienić na inny typ usługi tylko wtedy, gdy aplikacja kwalifikuje się obecnie do uruchomienia nowej usługi na pierwszym planie.
  • Usługa na pierwszym planie może w każdej chwili zmienić swój typ na shortService. W tym momencie rozpoczyna się limit czasu oczekiwania.

Limit czasu usługi shortService zaczyna się od momentu wywołania metody Service.startForeground(). Aplikacja powinna wywołać Service.stopSelf() lub Service.stopForeground() przed upływem limitu czasu. W przeciwnym razie wywoływany jest nowy Service.onTimeout(), co daje aplikacjom krótką okazję do wywołania metody stopSelf() lub stopForeground() w celu zatrzymania działania usługi.

W krótkim czasie po wywołaniu funkcji Service.onTimeout() aplikacja przechodzi w stan z pamięci podręcznej i nie jest już uznawana za działającą na pierwszym planie, chyba że użytkownik aktywnie z niej korzysta. W krótkim czasie po zapisaniu aplikacji w pamięci podręcznej, a aplikacja nie została zatrzymana, aplikacja otrzymuje błąd ANR. Wiadomość o błędzie ANR zawiera informację o elemencie FOREGROUND_SERVICE_TYPE_SHORT_SERVICE. Dlatego wdrożenie wywołania zwrotnego Service.onTimeout() uznaje się za sprawdzoną metodą.

Wywołanie zwrotne Service.onTimeout() nie występuje na Androidzie 13 i starszych wersjach. Jeśli na takich urządzeniach ta sama usługa działa, nie dochodzi do jej przekroczenia limitu czasu ani błędów ANR. Upewnij się, że usługa zatrzymuje się natychmiast po zakończeniu zadania przetwarzania, nawet jeśli nie odebrała jeszcze wywołania zwrotnego Service.onTimeout().

Pamiętaj, że jeśli limit czasu shortService nie jest przestrzegany, w aplikacji wystąpi błąd ANR, nawet jeśli mają uruchomione inne prawidłowe usługi na pierwszym planie lub inne uruchomione procesy cyklu życia aplikacji.

Jeśli aplikacja jest widoczna dla użytkownika lub spełnia jedno z wyjątków, które zezwalają na uruchamianie usług działających na pierwszym planie w tle, ponowne wywołanie metody Service.StartForeground() z parametrem FOREGROUND_SERVICE_TYPE_SHORT_SERVICE wydłuża czas oczekiwania o kolejne 3 minuty. Jeśli aplikacja nie jest widoczna dla użytkownika i nie spełnia jednego z wyjątków, każda próba uruchomienia kolejnej usługi na pierwszym planie (niezależnie od typu) powoduje wywołanie ForegroundServiceStartNotAllowedException.

Jeśli użytkownik wyłączy optymalizację baterii w Twojej aplikacji, nadal na niego wpływa limit czasu usługi shortService FGS.

Jeśli uruchomisz usługę działającej na pierwszym planie, która zawiera typ shortService i inny typ tej usługi, system zignoruje deklarację typu shortService. Usługa musi jednak spełniać wymagania wstępne innych zadeklarowanych typów. Więcej informacji znajdziesz w dokumentacji usług działających na pierwszym planie.

Specjalne zastosowanie

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>

System wykluczony

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:

Egzekwowanie zasad Google Play dotyczących korzystania z typów usług na pierwszym planie

If your app targets Android 14 or higher, you'll need to declare your app's foreground service types in the Play Console's app content page (Policy > App content). For more information on how to declare your foreground service types in Play Console, see Understanding foreground service and full-screen intent requirements.