Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Có 2 bước để chạy một dịch vụ trên nền trước từ ứng dụng của bạn. Trước tiên, bạn phải bắt đầu dịch vụ bằng cách gọi context.startForegroundService(). Sau đó, hãy để dịch vụ gọi ServiceCompat.startForeground() để tự chuyển thành dịch vụ trên nền trước.
Điều kiện tiên quyết
Tuỳ thuộc vào cấp độ API mà ứng dụng của bạn nhắm đến, có một số hạn chế về thời điểm ứng dụng có thể chạy một dịch vụ trên nền trước.
Các ứng dụng nhắm đến Android 12 (API cấp 31) trở lên không được phép bắt đầu một dịch vụ trên nền trước trong khi ứng dụng ở chế độ nền, ngoại trừ một số trường hợp cụ thể. Để biết thêm thông tin và thông tin về các trường hợp ngoại lệ đối với quy tắc này, hãy xem bài viết Các hạn chế khi khởi động dịch vụ trên nền trước từ nền.
Những ứng dụng nhắm đến Android 14 (API cấp 34) trở lên phải yêu cầu các quyền thích hợp cho loại dịch vụ trên nền trước. Khi ứng dụng cố gắng chuyển một dịch vụ lên nền trước, hệ thống sẽ kiểm tra các quyền thích hợp và gửi SecurityException nếu ứng dụng thiếu bất kỳ quyền nào. Ví dụ: nếu bạn cố gắng chạy một dịch vụ trên nền trước thuộc loại location, hệ thống sẽ kiểm tra để đảm bảo ứng dụng của bạn đã có quyền ACCESS_COARSE_LOCATION hoặc ACCESS_FINE_LOCATION. Tài liệu về loại dịch vụ trên nền trước liệt kê các điều kiện tiên quyết bắt buộc đối với từng loại dịch vụ trên nền trước.
Ra mắt dịch vụ
Để khởi chạy một dịch vụ trên nền trước, trước tiên, bạn phải khởi chạy dịch vụ đó dưới dạng một dịch vụ thông thường (không phải dịch vụ trên nền trước):
Kotlin
valintent=Intent(...)// Build the intent for the servicecontext.startForegroundService(intent)
Java
Contextcontext=getApplicationContext();Intentintent=newIntent(...);// Build the intent for the servicecontext.startForegroundService(intent);
Các điểm chính về mã
Đoạn mã này khởi chạy một dịch vụ. Tuy nhiên, dịch vụ này chưa chạy ở nền trước. Trong chính dịch vụ này, bạn cần gọi ServiceCompat.startForeground() để chuyển dịch vụ thành dịch vụ trên nền trước.
Đưa một dịch vụ lên nền trước
Sau khi một dịch vụ đang chạy, bạn cần gọi ServiceCompat.startForeground() để yêu cầu dịch vụ chạy ở nền trước. Thông thường, bạn sẽ gọi phương thức này trong phương thức onStartCommand() của dịch vụ.
ServiceCompat.startForeground() lấy các thông số sau:
Dịch vụ.
Một số nguyên dương xác định riêng biệt thông báo của dịch vụ trong thanh trạng thái.
Các loại dịch vụ trên nền trước mà bạn truyền đến startForeground()các loại được khai báo trong tệp kê khai, tuỳ thuộc vào trường hợp sử dụng cụ thể. Sau đó, nếu cần thêm các loại dịch vụ khác, bạn có thể gọi lại startForeground().
Ví dụ: giả sử một ứng dụng thể dục chạy dịch vụ theo dõi hoạt động chạy bộ luôn cần thông tin location, nhưng có thể cần hoặc không cần phát nội dung nghe nhìn. Bạn cần khai báo cả location và mediaPlayback 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 nên gọi startForeground() và chỉ truyền quyền ACCESS_FINE_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 tổ hợp theo bit của tất cả các loại dịch vụ trên nền trước (trong trường hợp này là ACCESS_FINE_LOCATION|FOREGROUND_SERVICE_MEDIA_PLAYBACK).
Ví dụ sau đây cho thấy mã mà một dịch vụ camera sẽ dùng để tự quảng bá thành dịch vụ trên nền trước:
Kotlin
classMyCameraService:Service(){privatefunstartForeground(){// Before starting the service as foreground check that the app has the// appropriate runtime permissions. In this case, verify that the user has// granted the CAMERA permission.valcameraPermission=PermissionChecker.checkSelfPermission(this,Manifest.permission.CAMERA)if(cameraPermission!=PermissionChecker.PERMISSION_GRANTED){// Without camera permissions the service cannot run in the foreground// Consider informing user or updating your app UI if visible.stopSelf()return}try{valnotification=NotificationCompat.Builder(this,"CHANNEL_ID")// Create the notification to display while the service is running.build()ServiceCompat.startForeground(/* service = */this,/* id = */100,// Cannot be 0/* notification = */notification,/* foregroundServiceType = */if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.R){ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA}else{0},)}catch(e:Exception){if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.S&&eisForegroundServiceStartNotAllowedException){// App not in a valid state to start foreground service// (e.g. started from bg)}// ...}}}
Java
publicclassMyCameraServiceextendsService{privatevoidstartForeground(){// Before starting the service as foreground check that the app has the// appropriate runtime permissions. In this case, verify that the user// has granted the CAMERA permission.intcameraPermission=ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA);if(cameraPermission==PackageManager.PERMISSION_DENIED){// Without camera permissions the service cannot run in the// foreground. Consider informing user or updating your app UI if// visible.stopSelf();return;}try{Notificationnotification=newNotificationCompat.Builder(this,"CHANNEL_ID")// Create the notification to display while the service// is running.build();inttype=0;if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.R){type=ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;}ServiceCompat.startForeground(/* service = */this,/* id = */100,// Cannot be 0/* notification = */notification,/* foregroundServiceType = */type);}catch(Exceptione){if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.S&&einstanceofForegroundServiceStartNotAllowedException){// App not in a valid state to start foreground service// (e.g started from bg)}// ...}}//...}
Các điểm chính về mã
Ứng dụng đã khai báo trong tệp kê khai rằng ứng dụng cần có quyền CAMERA. Tuy nhiên, ứng dụng cũng phải kiểm tra trong thời gian chạy để đảm bảo người dùng đã cấp quyền đó. Nếu thực sự không có các quyền chính xác, ứng dụng phải cho người dùng biết về vấn đề này.
Các loại dịch vụ trên nền trước khác nhau đã được ra mắt cùng với các phiên bản khác nhau của nền tảng Android. Mã này kiểm tra phiên bản Android mà ứng dụng đang chạy và yêu cầu các quyền thích hợp.
Mã này kiểm tra ForegroundServiceStartNotAllowedException trong trường hợp ứng dụng đang cố gắng khởi động một dịch vụ trên nền trước trong tình huống không được phép (ví dụ: nếu ứng dụng đang cố gắng chuyển dịch vụ lên nền trước trong khi ứng dụng đang ở chế độ nền).
Nội dung và mã mẫu trên trang này phải tuân thủ các giấy phép như mô tả trong phần Giấy phép nội dung. Java và OpenJDK là nhãn hiệu hoặc nhãn hiệu đã đăng ký của Oracle và/hoặc đơn vị liên kết của Oracle.
Cập nhật lần gần đây nhất: 2025-08-27 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-27 UTC."],[],[],null,["There are two steps to launching a foreground service from your app. First, you\nmust start the service by calling\n[`context.startForegroundService()`](/reference/android/content/Context#startForegroundService(android.content.Intent)). Then, have the\nservice call [`ServiceCompat.startForeground()`](/reference/androidx/core/app/ServiceCompat#startForeground(android.app.Service,int,android.app.Notification,int)) to promote\nitself into a foreground service.\n\nPrerequisites\n\nDepending on which API level your app targets, there are some restrictions on\nwhen an app can launch a foreground service.\n\n- Apps that target Android 12 (API level 31) or higher are not allowed to\n start a foreground service while the app is in the background, with a few\n specific exceptions. For more information, and information about the\n exceptions to this rule, see [Restrictions on starting a foreground service\n from the background](/develop/background-work/services/fgs/restrictions-bg-start).\n\n- Apps that target Android 14 (API level 34) or higher must request the\n appropriate\n permissions for the foreground service type. When the app attempts to\n promote a service to the foreground, the system checks for the appropriate\n permissions and throws throws [`SecurityException`](/reference/java/lang/SecurityException) if\n the app is missing any. For example, if you try to launch a foreground\n service of type `location`, the system checks to make sure your app already\n has either the `ACCESS_COARSE_LOCATION` or `ACCESS_FINE_LOCATION`\n permission. The [foreground service type](/develop/background-work/services/fgs/service-types) documentation lists the\n required prerequisites for each foreground service type.\n\nLaunch a service\n\nIn order to launch a foreground service, you must first launch it as an\nordinary (non-foreground) service: \n\nKotlin \n\n```kotlin\nval intent = Intent(...) // Build the intent for the service\ncontext.startForegroundService(intent)\n```\n\nJava \n\n```java\nContext context = getApplicationContext();\nIntent intent = new Intent(...); // Build the intent for the service\ncontext.startForegroundService(intent);\n```\n\nKey points about the code\n\n- The code snippet launches a service. However, the service is not yet running in the foreground. Inside the service itself, you need to call `ServiceCompat.startForeground()` to promote the service to a foreground service.\n\nPromote a service to the foreground\n\nOnce a service is running, you need to call\n[`ServiceCompat.startForeground()`](/reference/androidx/core/app/ServiceCompat#startForeground(android.app.Service,int,android.app.Notification,int)) to request that the service\nrun in the foreground. Ordinarily you would call this method in the service's\n[`onStartCommand()`](/reference/android/app/Service#onStartCommand(android.content.Intent,%20int,%20int)) method.\n\n`ServiceCompat.startForeground()` takes the following parameters:\n\n- The service.\n- A positive integer that uniquely identifies the service's notification in the status bar.\n- The [`Notification`](/reference/android/app/Notification) object itself.\n- The [foreground service type or types](/develop/background-work/services/fgs/service-types) identifying the work done by the service\n\n| **Note:** If you pass a foreground service type to `startForeground` that you did not declare in the manifest, the system throws `IllegalArgumentException`.\n\nThe foreground service types you pass to `startForeground()`\n[types declared in the manifest](/develop/background-work/services/fgs/service-types#declare-fgs), depending on the specific\nuse case. Then, if you need to add more service types, you can call\n`startForeground()` again.\n\nFor example, suppose a fitness app runs a running-tracker service that always\nneeds `location` information, but might or might not need to play media. You\nwould need to declare both `location` and `mediaPlayback` in the manifest. If a\nuser starts a run and just wants their location tracked, your app should call\n`startForeground()` and pass just the `ACCESS_FINE_LOCATION` permission. Then,\nif the user wants to start playing audio, call `startForeground()` again and\npass the bitwise combination of all the foreground service types (in this case,\n`ACCESS_FINE_LOCATION|FOREGROUND_SERVICE_MEDIA_PLAYBACK`).\n| **Note:** The status bar notification must use a priority of [`PRIORITY_LOW`](/reference/androidx/core/app/NotificationCompat#PRIORITY_LOW) or higher. If your app attempts to use a notification that has a lower priority than `PRIORITY_LOW`, the system adds a message to the notification drawer, alerting the user to the app's use of a foreground service.\n\nThe following example shows the code a camera service would use to promote\nitself to a foreground service: \n\nKotlin \n\n```kotlin\nclass MyCameraService: Service() {\n\n private fun startForeground() {\n // Before starting the service as foreground check that the app has the\n // appropriate runtime permissions. In this case, verify that the user has\n // granted the CAMERA permission.\n val cameraPermission =\n PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA)\n if (cameraPermission != PermissionChecker.PERMISSION_GRANTED) {\n // Without camera permissions the service cannot run in the foreground\n // Consider informing user or updating your app UI if visible.\n stopSelf()\n return\n }\n\n try {\n val notification = NotificationCompat.Builder(this, \"CHANNEL_ID\")\n // Create the notification to display while the service is running\n .build()\n ServiceCompat.startForeground(\n /* service = */ this,\n /* id = */ 100, // Cannot be 0\n /* notification = */ notification,\n /* foregroundServiceType = */\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.R) {\n ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA\n } else {\n 0\n },\n )\n } catch (e: Exception) {\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.S\n && e is ForegroundServiceStartNotAllowedException) {\n // App not in a valid state to start foreground service\n // (e.g. started from bg)\n }\n // ...\n }\n }\n}\n```\n\nJava \n\n```java\npublic class MyCameraService extends Service {\n\n private void startForeground() {\n // Before starting the service as foreground check that the app has the\n // appropriate runtime permissions. In this case, verify that the user\n // has granted the CAMERA permission.\n int cameraPermission =\n ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);\n if (cameraPermission == PackageManager.PERMISSION_DENIED) {\n // Without camera permissions the service cannot run in the\n // foreground. Consider informing user or updating your app UI if\n // visible.\n stopSelf();\n return;\n }\n\n try {\n Notification notification =\n new NotificationCompat.Builder(this, \"CHANNEL_ID\")\n // Create the notification to display while the service\n // is running\n .build();\n int type = 0;\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.R) {\n type = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;\n }\n ServiceCompat.startForeground(\n /* service = */ this,\n /* id = */ 100, // Cannot be 0\n /* notification = */ notification,\n /* foregroundServiceType = */ type\n );\n } catch (Exception e) {\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.S &&\n e instanceof ForegroundServiceStartNotAllowedException\n ) {\n // App not in a valid state to start foreground service\n // (e.g started from bg)\n }\n // ...\n }\n }\n\n //...\n}\n```\n\nKey points about the code\n\n- The app has already declared in the manifest that it needs the `CAMERA` permission. However, the app also has to check at runtime to make sure the user granted that permission. If the app does not actually have the correct permissions, it should let the user know about the problem.\n- Different foreground service types were introduced with different versions of the Android platform. This code checks what version of Android it's running on and requests the appropriate permissions.\n- The code checks for `ForegroundServiceStartNotAllowedException` in case it's trying to start a foreground service in a situation that's not allowed (for example, if it's trying to promote the service to the foreground [while\n the app is in the background](/develop/background-work/services/fgs/restrictions-bg-start))."]]