public final class ForegroundService

  1. Object
  2. ForegroundService

Runs a long lived task while a persistent system notification is shown to the user. This is an Android foreground service. On iOS, which has no foreground service concept, the task runs under a limited background execution window accompanied by a local notification (best effort); check #isSupported() to detect full support.

Usage

ForegroundService svc = ForegroundService.start("downloads", "Downloading", "Please wait", null,
    service -> {
        for (int i = 0; i <= 100; i++) {
            service.updateNotification("Downloading", i + "%");
            // ... do a chunk of work ...
        }
    });
// the service auto-stops when the task returns, or call svc.stop() early

Nested types

interface ForegroundService.TaskThe long running task executed by a foreground service.

Methods

public static ForegroundService start(String channelId, String title, String body, String iconName, ForegroundService.Task task)Starts a foreground service that shows a persistent notification and runs the task on a background thread.
public void updateNotification(String title, String body)Updates the text of the foreground service notification.
public void stop()Stops the service and removes its notification.
public boolean isRunning()Returns true if the service is currently running.
public static boolean isSupported()Returns true if the current platform fully supports foreground services.

Inherited methods

Method details

start

public static ForegroundService start(String channelId, String title, String body, String iconName, ForegroundService.Task task)
Starts a foreground service that shows a persistent notification and runs the task on a background thread.

Parameters

channelId String
the notification channel id to post the notification on
title String
the notification title
body String
the notification body
iconName String
the small icon resource name, or null for the default app icon
task ForegroundService.Task
the work to run

Returns

the running service handle

updateNotification

public void updateNotification(String title, String body)
Updates the text of the foreground service notification.

Parameters

title String
the new title
body String
the new body

stop

public void stop()
Stops the service and removes its notification.

isRunning

public boolean isRunning()
Returns true if the service is currently running.

Returns

true if running

isSupported

public static boolean isSupported()
Returns true if the current platform fully supports foreground services.

Returns

true if foreground services are supported