public final class ForegroundService
- Object
- 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.Task | The 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
channelIdString- the notification channel id to post the notification on
titleString- the notification title
bodyString- the notification body
iconNameString- the small icon resource name, or null for the default app icon
taskForegroundService.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
titleString- the new title
bodyString- 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