- How to properly cancel notification of ended Foreground Service in Android 8
- Foreground services
- Services that show a notification immediately
- Request the foreground service permission
- Start a foreground service
- Kotlin
- Kotlin
- Restrictions on background starts
- Check whether your app performs background starts
- Update your app’s logic
- Exemptions from background start restrictions
- Remove a service from the foreground
- Declare foreground service types
- Example using location and camera
- Kotlin
- Example using location, camera, and microphone
- Kotlin
- Add foreground service types of Work Manager workers
- Restricted access to location, camera, and microphone
- Exemptions from the restrictions
- Determine which services are affected in your app
- Android Foreground Service Example
- 1. Android Foreground Service Example.
- 2. Example Source Code.
- 2.1 Android Foreground Service Class.
- 2.2 Main Activity.
- 2.3 Layout XML File.
- 2.4 Android Manifest Xml File.
- 2.5 Assign FOREGROUND_SERVICE Permission.
How to properly cancel notification of ended Foreground Service in Android 8
My App is using new Foreground service design introduced in Android 8.
I have a problem with cancelling notification displayed in the system tray during the service execution. Some services are still causing that notification related to service freezing on the notification bar even if service is not running.
I would like to ask on some recommendations how to do it in the right way because Android Documentation is not clear in this case.
Below is mentioned my approach to execution of service and displaying/ cancelling the notification. Any suggestion is welcome.
Note: I added timeout method to UserManualCheckService to force invocation of the stopSelf() method.
1) Service is started using Worker Manager as an instance of Worker:
Worker example
2) Service example
Service is downloading some data using HTTP request. Error and Success state of download is ended by using stopSelf() method which should trigger onDestroy() event in parent BaseIntentService service.
BaseIntentService
Parent service for all background services. Calling stopSelf() on children is passed to parent and catched in onDestroy() where is service stopped and notification SHOULD be each time canceled.
Starting execution of the Foreground Service using the helper class:
Displaying notification:
Stopping service is done in this way:
Cancelling notification method called from BaseIntentService onDestroy()
Источник
Foreground services
Foreground services perform operations that are noticeable to the user.
Foreground services show a status bar notification, so that users are actively aware that your app is performing a task in the foreground and is consuming system resources. The notification cannot be dismissed unless the service is either stopped or removed from the foreground.
Devices that run Android 12 (API level 31) or higher provide a streamlined experience for short-running foreground services. On these devices, the system waits 10 seconds before showing the notification associated with a foreground service. There are a few exceptions; several types of services always display a notification immediately.
Examples of apps that would use foreground services include the following:
- A music player app that plays music in a foreground service. The notification might show the current song that is being played.
- A fitness app that records a user’s run in a foreground service, after receiving permission from the user. The notification might show the distance that the user has traveled during the current fitness session.
You should only use a foreground service when your app needs to perform a task that is noticeable by the user even when they’re not directly interacting with the app. If the action is of low enough importance that you want to use a minimum-priority notification, create a background task instead.
This document describes the required permission for using foreground services, how to start a foreground service and remove it from the background, how to associate certain use cases with foreground service types, and the access restrictions that take effect when you start a foreground service from an app that’s running in the background.
Services that show a notification immediately
If a foreground service has at least one of the following characteristics, the system shows the associated notification immediately after the service starts, even on devices that run Android 12 or higher:
- The service is associated with a notification that includes action buttons.
- The service has a foregroundServiceType of mediaPlayback , mediaProjection , or phoneCall .
- The service provides a use case related to phone calls, navigation, or media playback, as defined in the notification’s category attribute.
- The service has opted out of the behavior change by passing FOREGROUND_SERVICE_IMMEDIATE into setForegroundServiceBehavior() when setting up the notification.
Request the foreground service permission
Apps that target Android 9 (API level 28) or higher and use foreground services must request the FOREGROUND_SERVICE permission, as shown in the following code snippet. This is a normal permission, so the system automatically grants it to the requesting app.
Start a foreground service
Before you request the system to run a service as a foreground service, start the service itself:
Kotlin
Inside the service, usually in onStartCommand() , you can request that your service run in the foreground. To do so, call startForeground() . This method takes two parameters: a positive integer that uniquely identifies the notification in the status bar and the Notification object itself.
Note: The status bar notification must use a priority of PRIORITY_LOW or higher. If your app attempts to use a notification that has a lower priority, the system adds a message to the notification drawer, alerting the user to the app’s use of a foreground service.
Here is an example:
Kotlin
Restrictions on background starts
Apps that target Android 12 (API level 31) or higher can’t start foreground services while running in the background, except for a few special cases. If an app tries to start a foreground service while the app is running in the background, and the foreground service doesn’t satisfy one of the exceptional cases, the system throws a ForegroundServiceStartNotAllowedException .
Check whether your app performs background starts
To better understand when your app attempts to launch a foreground service while running in the background, you can enable notifications that appear each time this behavior occurs. To do so, execute the following ADB command on the development machine connected to your test device or emulator:
Update your app’s logic
If you discover that your app starts foreground services while running from the background, update your app’s logic to use WorkManager. To view an example of how to update your app, look through the WorkManagerSample on GitHub.
Exemptions from background start restrictions
In the following situations, your app can start foreground services even while your app is running in the background:
- Your app transitions from a user-visible state, such as an activity.
- Your app can start an activity from the background, except for the case where the app has an activity in the back stack of an existing task.
Your app receives a high-priority message using Firebase Cloud Messaging.
Note: When your app is in the frequent bucket or a more restrictive bucket, your high-priority FCM messages might be downgraded to normal priority. If the message’s priority is downgraded, your app can’t start a foreground service. To check the priority of an FCM message that your app receives, call getPriority() .
The user performs an action on a UI element related to your app. For example, they might interact with a bubble, notification, widget, or activity.
Your app invokes an exact alarm to complete an action that the user requests.
Your app is the device’s current input method.
Your app receives an event that’s related to geofencing or activity recognition transition.
Your app receives the ACTION_TIMEZONE_CHANGED , ACTION_TIME_CHANGED , or ACTION_LOCALE_CHANGED intent action in a broadcast receiver.
Your app receives a Bluetooth broadcast that requires the BLUETOOTH_CONNECT or BLUETOOTH_SCAN permissions.
Apps with certain system roles or permission, such as device owners and profile owners.
Your app uses the Companion Device Manager and declares the REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND permission or the REQUEST_COMPANION_RUN_IN_BACKGROUND permission. Whenever possible, use REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND .
The user turns off battery optimizations for your app. You can help users find this option by sending them to your app’s App info page in system settings. To do so, invoke an intent that contains the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent action.
Remove a service from the foreground
To remove the service from the foreground, call stopForeground() . This method takes a boolean, which indicates whether to remove the status bar notification as well. Note that the service continues to run.
If you stop the service while it’s running in the foreground, its notification is removed.
Declare foreground service types
If your app targets Android 10 (API level 29) or higher and accesses location information in a foreground service, declare the location foreground service type as an attribute of your component.
If your app targets Android 11 (API level 30) or higher and accesses the camera or microphone in a foreground service, declare the camera or microphone foreground service types, respectively, as attributes of your component.
By default, when you call startForeground() at runtime, the system allows access to each of the service types that you declare in the app manifest. You can choose to limit access to a subset of the declared service types, as shown in the code snippets within the following sections.
Example using location and camera
If a foreground service in your app needs to access the device’s location and camera, declare the service as shown in the following snippet:
At runtime, if the foreground service only needs access to a subset of the types declared in the manifest, you can limit the service’s access using the logic in the following code snippet:
Kotlin
Example using location, camera, and microphone
If a foreground service needs to access location, the camera, and the microphone, declare the service as shown in the following snippet:
At runtime, if the foreground service only needs access to a subset of the types declared in the manifest, you can limit the service’s access using the logic in the following code snippet:
Kotlin
Add foreground service types of Work Manager workers
If your app uses Work Manager and has a long-running worker that requires access to location, camera, or microphone, follow the steps to add a foreground service type to a long-running worker, and specify the additional or alternative foreground service types that your worker uses. You can choose from the following foreground service types:
Restricted access to location, camera, and microphone
To help protect user privacy, Android 11 (API level 30) introduces limitations to when a foreground service can access the device’s location, camera, or microphone. When your app starts a foreground service while the app is running in the background, the foreground service has the following limitations:
- Unless the user has granted the ACCESS_BACKGROUND_LOCATION permission to your app, the foreground service cannot access location.
- The foreground service cannot access the microphone or camera.
Exemptions from the restrictions
In some situations, even if a foreground service is started while the app is running in the background, it can still access location, camera, and microphone information while the app is running in the foreground («while-in-use»). In these same situations, if the service declares a foreground service type of location and is started by an app that has the ACCESS_BACKGROUND_LOCATION permission, this service can access location information all the time, even when the app is running in the background.
The following list contains these situations:
- The service is started by a system component.
- The service is started by interacting with app widgets.
- The service is started by interacting with a notification.
- The service is started as a PendingIntent that is sent from a different, visible app.
- The service is started by an app that is a device policy controller that is running in device owner mode.
- The service is started by an app which provides the VoiceInteractionService .
- The service is started by an app that has the START_ACTIVITIES_FROM_BACKGROUND privileged permission.
Determine which services are affected in your app
When testing your app, start its foreground services. If a started service has restricted access to location, microphone, and camera, the following message appears in Logcat:
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Android Foreground Service Example
Android foreground service is an android service object. It always runs in the foreground, this can avoid service objects being recycled by the android system when android os does not have enough resources. Android foreground service can interact with users through notification. It is usually used in a music player, file downloader, etc which user has few interactions with the player service but the service should not be stopped and recycled.
1. Android Foreground Service Example.
- There are 2 buttons in the Android app. When you click the START FOREGROUND SERVICE button, it will create and start a foreground service.
- The foreground service will show a head-up notification which will pop up at the screen top with max priority. The notification is also a text-style notification.
- There are two buttons in the notification, clicking each button will display a toast message at the screen bottom. When you click the STOP FOREGROUND SERVICE button, it will stop the service and remove the notification.
2. Example Source Code.
- The below source files are the example project files.
- There are two java files in this example MyForeGroundService.java & CreateForegroundServiceActivity.java.
- MyForeGroundService.java: This is the android foreground service class. It overrides the android.app.Service.onStartCommand(Intent intent, int flags, int startId) method. This method will be invoked when the activity invokes the startService(intent) method.
- In the onStartCommand method, it will check which button has been pressed by the intent.getAction() method returned value, and then invokes a related method such as startForegroundService().
- In the startForegroundService() method, to make the service object run in the foreground, it will create a Notification object, and then call the startForeground() method to make the service object run as foreground service.
- In the stopForegroundService() method, it will stop the MyForeGroundService service object from the foreground service by invoking the stopForeground(true) method, this will also remove the notification object. Then it will call the stopSelf() method to stop the service object.
- CreateForegroundServiceActivity.java: This is the activity class java file. It will be created when the android app starts. It will listen to the two buttons on-click event, and when one button is clicked, it will start the MyForeGroundService object by creating an Intent object, setting the intent object action, and then calling the startService(intent) method to start the service object. Then the MyForeGroundService object will be created, and its onStartCommand method will be invoked.
2.1 Android Foreground Service Class.
- MyForeGroundService.java
2.2 Main Activity.
- CreateForegroundServiceActivity.java
2.3 Layout XML File.
- activity_create_foreground_service.xml
2.4 Android Manifest Xml File.
- AndroidManifest.xml
2.5 Assign FOREGROUND_SERVICE Permission.
- If your android app os version is higher than or equal to level 26, you need to assign FOREGROUND_SERVICE permission in your android app to avoid crashes.
- To implement this, you should add the below XML snippet in the AndroidManifest.xml file.
Reference
This site uses Akismet to reduce spam. Learn how your comment data is processed.
This gives error for Android O & above versions.
I am facing error as : Developer warning for package “com.xxx.xxx”. Failed to post notification on channel “null”.
Android O Need Notification Channel like that
private fun startForegroundService() <
Log.d(TAG_FOREGROUND_SERVICE, “Start foreground service.”)
// Create notification default intent.
val intent = Intent()
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val channelId = “NOTIFICATION_CHANNEL_NAME”
// Create notification builder.
val builder = NotificationCompat.Builder(this,channelId)
// Make notification show big text.
val bigTextStyle = NotificationCompat.BigTextStyle()
bigTextStyle.setBigContentTitle(“Music player implemented by foreground service.”)
bigTextStyle.bigText(“Android foreground service is a android service which can run in foreground always, it can be controlled by user via notification.”)
// Set big text style.
builder.setStyle(bigTextStyle)
builder.setWhen(System.currentTimeMillis())
builder.setSmallIcon(R.mipmap.ic_launcher)
val largeIconBitmap = BitmapFactory.decodeResource(resources, R.drawable.abc_ic_ab_back_material)
builder.setLargeIcon(largeIconBitmap)
// Make the notification max priority.
builder.priority = Notification.PRIORITY_MAX
// Make head-up notification.
builder.setFullScreenIntent(pendingIntent, true)
// Add Play button intent in notification.
val playIntent = Intent(this, MyForeGroundService::class.java)
playIntent.action = ACTION_PLAY
val pendingPlayIntent = PendingIntent.getService(this, 0, playIntent, 0)
val playAction = NotificationCompat.Action(android.R.drawable.ic_media_play, “Play”, pendingPlayIntent)
builder.addAction(playAction)
// Add Pause button intent in notification.
val pauseIntent = Intent(this, MyForeGroundService::class.java)
pauseIntent.action = ACTION_PAUSE
val pendingPrevIntent = PendingIntent.getService(this, 0, pauseIntent, 0)
val prevAction = NotificationCompat.Action(android.R.drawable.ic_media_pause, “Pause”, pendingPrevIntent)
builder.addAction(prevAction)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) <
val channel = NotificationChannel(
channelId, “NOTIFICATION_CHANNEL_NAME”,
NotificationManager.IMPORTANCE_HIGH
).apply <
enableLights(true)
lightColor = Color.DKGRAY
setShowBadge(true)
enableVibration(true)
vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
>
notificationManager.createNotificationChannel(channel)
>
// Build the notification.
val notification = builder.build()
// Start foreground service.
startForeground(1, notification)
>
Источник