Partager via


Context.StartForegroundService(Intent) Method

Definition

Similar to #startService(Intent), but with an implicit promise that the Service will call android.app.Service#startForeground(int, android.app.Notification) startForeground(int, android.app.Notification) once it begins running.

[Android.Runtime.Register("startForegroundService", "(Landroid/content/Intent;)Landroid/content/ComponentName;", "GetStartForegroundService_Landroid_content_Intent_Handler", ApiSince=26)]
public abstract Android.Content.ComponentName? StartForegroundService (Android.Content.Intent? service);
[<Android.Runtime.Register("startForegroundService", "(Landroid/content/Intent;)Landroid/content/ComponentName;", "GetStartForegroundService_Landroid_content_Intent_Handler", ApiSince=26)>]
abstract member StartForegroundService : Android.Content.Intent -> Android.Content.ComponentName

Parameters

service
Intent

Identifies the service to be started. The Intent must be fully explicit (supplying a component name). Additional values may be included in the Intent extras to supply arguments along with this specific start call.

Returns

If the service is being started or is already running, the ComponentName of the actual service that was started is returned; else if the service does not exist null is returned.

Attributes

Remarks

Similar to #startService(Intent), but with an implicit promise that the Service will call android.app.Service#startForeground(int, android.app.Notification) startForeground(int, android.app.Notification) once it begins running. The service is given an amount of time comparable to the ANR interval to do this, otherwise the system will automatically crash the process, in which case an internal exception ForegroundServiceDidNotStartInTimeException is logged on logcat on devices running SDK Version android.os.Build.VERSION_CODES#S or later. On older Android versions, an internal exception RemoteServiceException is logged instead, with a corresponding message.

Unlike the ordinary #startService(Intent), this method can be used at any time, regardless of whether the app hosting the service is in a foreground state.

<div class="caution">

<strong>Note:</strong> Beginning with SDK Version android.os.Build.VERSION_CODES#S, apps targeting SDK Version android.os.Build.VERSION_CODES#S or higher are not allowed to start foreground services from the background. See

Behavior changes: Apps targeting Android 12

for more details. </div>

Java documentation for android.content.Context.startForegroundService(android.content.Intent).

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Applies to