Bắt buộc phải có loại dịch vụ trên nền trước

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.

Khai báo quyền mới để sử dụng các loại dịch vụ trên nền trước

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.

Cung cấp loại dịch vụ trên nền trước trong thời gian chạy

Phương pháp hay nhất cho các ứng dụng có bắt đầu dịch vụ trên nền trước là sử dụng phiên bản ServiceCompat của startForeground() (có trong androidx-core 1.12 trở lên), trong đó bạn truyền một số nguyên bitwise của các kiểu dịch vụ trên nền trước. Bạn có thể chọn truyền một hoặc nhiều giá trị tương ứng với từng kiểu.

Thường thì bạn chỉ nên khai báo các kiểu cần thiết cho một trường hợp sử dụng cụ thể. Điều này giúp bạn dễ dàng đáp ứng các kỳ vọng của hệ thống đối với từng loại dịch vụ trên nền trước. Trong trường hợp sử dụng nhiều kiểu để bắt đầu dịch vụ trên nền trước, thì dịch vụ trên nền trước đó phải tuân thủ các yêu cầu thực thi trên nền tảng của tất cả kiểu.

ServiceCompat.startForeground(0, notification, FOREGROUND_SERVICE_TYPE_LOCATION)

Nếu kiểu dịch vụ trên nền trước không được chỉ định trong lệnh gọi, thì kiểu này sẽ mặc định là các giá trị được xác định trong tệp kê khai. Nếu bạn không chỉ định loại dịch vụ trong tệp kê khai, hệ thống sẽ gửi MissingForegroundServiceTypeException.

Nếu dịch vụ trên nền trước cần các quyền mới sau khi bạn khởi chạy, bạn nên gọi lại startForeground() và thêm các loại dịch vụ mới. Ví dụ: giả sử một ứng dụng thể dục chạy một dịch vụ theo dõi chạy bộ luôn cần thông tin location, nhưng có thể cần hoặc không cần quyền media. Bạn cần khai báo cả locationmediaPlayback trong tệp kê khai. Nếu người dùng bắt đầu chạy và chỉ muốn theo dõi vị trí của họ, thì ứng dụng của bạn sẽ gọi startForeground() và chỉ truyền loại dịch vụ location. Sau đó, nếu người dùng muốn bắt đầu phát âm thanh, hãy gọi lại startForeground() và truyền location|mediaPlayback.

Kiểm tra thời gian chạy của hệ thống

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.

Trường hợp sử dụng dự kiến và biện pháp thực thi đối với từng loại dịch vụ trên nền trước

Để sử dụng một kiểu dịch vụ trên nền trước nhất định, bạn phải khai báo một quyền cụ thể trong tệp kê khai, bạn phải đáp ứng các yêu cầu cụ thể về thời gian chạy, cũng như ứng dụng của bạn phải đáp ứng một trong các nhóm trường hợp sử dụng dự kiến cho kiểu đó. Các phần sau giải thích quyền bạn phải khai báo, các điều kiện tiên quyết về thời gian chạy và các trường hợp sử dụng dự kiến của từng kiểu.

Máy ảnh

Loại dịch vụ trên nền trước cần khai báo trong tệp kê khai trong android:foregroundServiceType
camera
Quyền khai báo trong tệp kê khai
FOREGROUND_SERVICE_CAMERA
Hằng số để truyền đến startForeground()
FOREGROUND_SERVICE_TYPE_CAMERA
Điều kiện tiên quyết về thời gian chạy

Yêu cầu và được cấp quyền khi bắt đầu chạy CAMERA

Lưu ý: Quyền khi bắt đầu chạy CAMERA phải tuân theo các quy định hạn chế khi đang sử dụng. Vì lý do này, bạn không thể tạo dịch vụ trên nền trước camera khi ứng dụng đang chạy ở chế độ nền, ngoại trừ một số trường hợp ngoại lệ. Để biết thêm thông tin, hãy xem phần Hạn chế khi khởi động các dịch vụ trên nền trước cần quyền khi đang sử dụng.

Mô tả

Tiếp tục truy cập vào máy ảnh ở chế độ nền, chẳng hạn như các ứng dụng trò chuyện video cho phép thực thi đa nhiệm.

Thiết bị đã kết nối

Loại dịch vụ trên nền trước cần khai báo trong tệp kê khai theo
android:foregroundServiceType
connectedDevice
Quyền khai báo trong tệp kê khai
FOREGROUND_SERVICE_CONNECTED_DEVICE
Hằng số để truyền đến startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
Điều kiện tiên quyết về thời gian chạy

Ít nhất một trong các điều kiện sau phải đúng:

Nội dung mô tả

Các hoạt động tương tác với thiết bị bên ngoài cần có kết nối Bluetooth, NFC, IR, USB hoặc kết nối mạng.

Lựa chọn thay thế

Nếu ứng dụng của bạn cần chuyển dữ liệu liên tục sang một thiết bị bên ngoài, hãy cân nhắc sử dụng trình quản lý thiết bị đồng hành. Sử dụng API hiện diện của thiết bị đồng hành để giúp ứng dụng của bạn luôn chạy trong khi thiết bị đồng hành ở trong phạm vi.

Nếu ứng dụng của bạn cần quét tìm thiết bị Bluetooth, hãy cân nhắc sử dụng API quét Bluetooth.

Đồng bộ hoá dữ liệu

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.

Sức khoẻ

Loại dịch vụ trên nền trước cần khai báo trong tệp kê khai theo
android:foregroundServiceType
health
Quyền khai báo trong tệp kê khai
FOREGROUND_SERVICE_HEALTH
Hằng số để truyền đến startForeground()
FOREGROUND_SERVICE_TYPE_HEALTH
Điều kiện tiên quyết về thời gian chạy

Ít nhất một trong các điều kiện sau phải đúng:

Lưu ý: Quyền khi bắt đầu chạy ĐỌC dựa trên cảm biến và BODY_SENSORS phải tuân thủ các hạn chế khi đang sử dụng. Vì lý do này, bạn không thể tạo một dịch vụ trên nền trước health sử dụng cảm biến cơ thể trong khi ứng dụng của bạn đang chạy ở chế độ nền, trừ phi bạn đã được cấp quyền BODY_SENSORS_BACKGROUND (API cấp 33 đến 35) hoặc READ_HEALTH_DATA_IN_BACKGROUND (API cấp 36 trở lên). Để biết thêm thông tin, hãy xem phần Hạn chế khi khởi động các dịch vụ trên nền trước cần quyền khi đang sử dụng.

Mô tả

Trường hợp sử dụng lâu dài bất kỳ để hỗ trợ các ứng dụng trong danh mục thể dục (ví dụ: trình theo dõi bài tập thể dục).

Vị trí

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:

Note: In order to check that the user has enabled location services as well as granted access to the runtime permissions, use PermissionChecker#checkSelfPermission()

Note: The location runtime permissions are subject to while-in-use restrictions. For this reason, you cannot create a location foreground service while your app is in the background, unless you've been granted the ACCESS_BACKGROUND_LOCATION runtime permission. For more information, see Restrictions on starting foreground services that need while-in-use 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.

Nội dung nghe nhìn

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.

Chiếu nội dung nghe nhìn

Loại dịch vụ trên nền trước cần khai báo trong tệp kê khai theo
android:foregroundServiceType
mediaProjection
Quyền khai báo trong tệp kê khai
FOREGROUND_SERVICE_MEDIA_PROJECTION
Hằng số để truyền đến startForeground()
FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
Điều kiện tiên quyết về thời gian chạy

Gọi phương thức createScreenCaptureIntent() trước khi bắt đầu dịch vụ trên nền trước. Thao tác này sẽ hiển thị thông báo cấp quyền cho người dùng; người dùng phải cấp quyền thì bạn mới có thể tạo dịch vụ.

Sau khi tạo dịch vụ trên nền trước, bạn có thể gọi MediaProjectionManager.getMediaProjection().

Mô tả

Chiếu nội dung tới màn hình phụ hoặc thiết bị bên ngoài bằng các API MediaProjection. Nội dung này không nhất thiết chỉ là nội dung đa phương tiện.

Lựa chọn thay thế

Để truyền trực tuyến nội dung nghe nhìn sang một thiết bị khác, hãy sử dụng SDK Google Cast.

Micrô

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.

Cuộc gọi điện thoại

Loại dịch vụ trên nền trước cần khai báo trong tệp kê khai theo
android:foregroundServiceType
phoneCall
Quyền khai báo trong tệp kê khai
FOREGROUND_SERVICE_PHONE_CALL
Hằng số để truyền đến startForeground()
FOREGROUND_SERVICE_TYPE_PHONE_CALL
Điều kiện tiên quyết về thời gian chạy

Ít nhất một trong các điều kiện sau phải đúng:

  • Ứng dụng là ứng dụng quay số mặc định thông qua vai trò ROLE_DIALER.
Mô tả

Tiếp tục cuộc gọi đang diễn ra bằng các API ConnectionService.

Lựa chọn thay thế

Nếu bạn cần thực hiện cuộc gọi điện thoại, video hoặc VoIP, hãy cân nhắc sử dụng thư viện android.telecom.

Cân nhắc sử dụng CallScreeningService để sàng lọc cuộc gọi.

Nhắn tin từ xa

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.

Dịch vụ ngắn

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.

Cách sử dụng đặc biệt

Loại dịch vụ trên nền trước cần khai báo trong tệp kê khai trong
android:foregroundServiceType
specialUse
Quyền khai báo trong tệp kê khai
FOREGROUND_SERVICE_SPECIAL_USE
Hằng số để truyền đến startForeground()
FOREGROUND_SERVICE_TYPE_SPECIAL_USE
Điều kiện tiên quyết về thời gian chạy
Không có
Nội dung mô tả

Bao gồm mọi trường hợp sử dụng dịch vụ trên nền trước hợp lệ không thuộc các loại dịch vụ trên nền trước khác.

Ngoài việc khai báo loại dịch vụ trên nền trước FOREGROUND_SERVICE_TYPE_SPECIAL_USE, nhà phát triển nên khai báo các trường hợp sử dụng trong tệp kê khai. Để làm vậy, họ cần chỉ định phần tử <property> trong phần tử <service>. Các giá trị này và trường hợp sử dụng tương ứng sẽ được xem xét khi bạn gửi ứng dụng trong Google Play Console. Việc sử dụng yêu cầu của bạn là theo mẫu tuỳ ý và bạn cần đảm bảo cung cấp đủ để cho nhân viên đánh giá biết lý do bạn cần sử dụng specialUse loại.

<service android:name="fooService" android:foregroundServiceType="specialUse">
  <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
      android:value="explanation_for_special_use"/>
</service>

Được miễn trừ hệ thống

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.

Phương thức thực thi chính sách của Google Play đối với việc sử dụng các loại dịch vụ trên nền trước

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.