Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Das Starten eines Vordergrunddienstes über Ihre App erfolgt in zwei Schritten. Zuerst müssen Sie den Dienst durch Aufrufen von context.startForegroundService() starten. Lassen Sie den Dienst dann ServiceCompat.startForeground() aufrufen, um ihn in einen Vordergrunddienst zu befördern.
Voraussetzungen
Je nachdem, auf welche API-Ebene Ihre App ausgerichtet ist, gelten einige Einschränkungen dafür, wann eine App einen Dienst im Vordergrund starten kann.
Apps, die auf Android 12 (API‑Level 31) oder höher ausgerichtet sind, dürfen keinen Dienst im Vordergrund starten, während die App im Hintergrund ausgeführt wird. Es gibt jedoch einige spezifische Ausnahmen. Weitere Informationen und Informationen zu den Ausnahmen von dieser Regel finden Sie unter Einschränkungen beim Starten eines Vordergrunddienstes im Hintergrund.
Apps, die auf Android 14 (API‑Level 34) oder höher ausgerichtet sind, müssen die entsprechenden Berechtigungen für den Typ des Dienstes im Vordergrund anfordern. Wenn die App versucht, einen Dienst in den Vordergrund zu verschieben, prüft das System, ob die entsprechenden Berechtigungen vorhanden sind, und löst SecurityException aus, wenn der App Berechtigungen fehlen. Wenn Sie beispielsweise versuchen, einen Dienst vom Typ location im Vordergrund zu starten, prüft das System, ob Ihre App bereits die Berechtigung ACCESS_COARSE_LOCATION oder ACCESS_FINE_LOCATION hat. In der Dokumentation zu Typen von Diensten im Vordergrund sind die erforderlichen Voraussetzungen für jeden Typ aufgeführt.
Dienst starten
Wenn Sie einen Dienst im Vordergrund starten möchten, müssen Sie ihn zuerst als normalen (nicht im Vordergrund ausgeführten) Dienst starten:
Kotlin
valintent=Intent(...)// Build the intent for the servicecontext.startForegroundService(intent)
Java
Contextcontext=getApplicationContext();Intentintent=newIntent(...);// Build the intent for the servicecontext.startForegroundService(intent);
Wichtige Punkte zum Code
Mit dem Code-Snippet wird ein Dienst gestartet. Der Dienst wird jedoch noch nicht im Vordergrund ausgeführt. Im Dienst selbst müssen Sie ServiceCompat.startForeground() aufrufen, um den Dienst zu einem Dienst im Vordergrund zu machen.
Dienst in den Vordergrund rücken
Sobald ein Dienst ausgeführt wird, müssen Sie ServiceCompat.startForeground() aufrufen, um anzufordern, dass der Dienst im Vordergrund ausgeführt wird. Normalerweise würden Sie diese Methode in der onStartCommand()-Methode des Dienstes aufrufen.
ServiceCompat.startForeground() verwendet die folgenden Parameter:
Der Dienst.
Eine positive Ganzzahl, die die Benachrichtigung des Dienstes in der Statusleiste eindeutig identifiziert.
Die Typen von Diensten im Vordergrund, die Sie an startForeground() übergeben, müssen je nach Anwendungsfall im Manifest deklariert sein. Wenn Sie weitere Diensttypen hinzufügen müssen, können Sie startForeground() noch einmal aufrufen.
Angenommen, eine Fitness-App führt einen Lauf-Tracker-Dienst aus, der immer location-Informationen benötigt, aber möglicherweise keine Medien abspielen muss. Sie müssen sowohl location als auch mediaPlayback im Manifest deklarieren. Wenn ein Nutzer einen Lauf startet und nur seinen Standort erfassen möchte, sollte Ihre App startForeground() aufrufen und nur die Berechtigung ACCESS_FINE_LOCATION übergeben. Wenn der Nutzer dann Audio abspielen möchte, rufen Sie startForeground() noch einmal auf und übergeben Sie die bitweise Kombination aller Arten von Diensten im Vordergrund (in diesem Fall ACCESS_FINE_LOCATION|FOREGROUND_SERVICE_MEDIA_PLAYBACK).
Das folgende Beispiel zeigt den Code, den ein Kameradienst verwenden würde, um sich selbst zu einem Dienst im Vordergrund zu machen:
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)}// ...}}//...}
Wichtige Punkte zum Code
In der Manifestdatei der App wurde bereits deklariert, dass die Berechtigung CAMERA erforderlich ist. Die App muss jedoch auch zur Laufzeit prüfen, ob der Nutzer diese Berechtigung erteilt hat. Wenn die App nicht die richtigen Berechtigungen hat, sollte sie den Nutzer über das Problem informieren.
Mit verschiedenen Versionen der Android-Plattform wurden verschiedene Arten von Vordergrunddiensten eingeführt. Dieser Code prüft, welche Android-Version verwendet wird, und fordert die entsprechenden Berechtigungen an.
Der Code prüft auf ForegroundServiceStartNotAllowedException, falls versucht wird, einen Dienst im Vordergrund in einer Situation zu starten, die nicht zulässig ist (z. B. wenn versucht wird, den Dienst in den Vordergrund zu verschieben, während die App im Hintergrund ausgeführt wird).
Alle Inhalte und Codebeispiele auf dieser Seite unterliegen den Lizenzen wie im Abschnitt Inhaltslizenz beschrieben. Java und OpenJDK sind Marken oder eingetragene Marken von Oracle und/oder seinen Tochtergesellschaften.
Zuletzt aktualisiert: 2025-08-27 (UTC).
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Benötigte Informationen nicht gefunden","missingTheInformationINeed","thumb-down"],["Zu umständlich/zu viele Schritte","tooComplicatedTooManySteps","thumb-down"],["Nicht mehr aktuell","outOfDate","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Problem mit Beispielen/Code","samplesCodeIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 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))."]]