I want to create a service and make it run in the foreground.
Most example codes have notifications on it. But I don't want to show any notification. Is that possible?
Can you give me some examples? Are there any alternatives?
My app service is doing mediaplayer. How to make system not kill my service except the app kill it itself (like pausing or stopping the music by button).
setContentText("To hide me, click and uncheck \"Hidden Notification Service\"") . setContentIntent(pendingIntent) . setSmallIcon(R. mipmap.
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. Devices that run Android 12 (API level 31) or higher provide a streamlined experience for short-running foreground services.
Inside the onReceive() method I call stopforeground(true) and it hides the notification. And then stopself() to stop the service.
As a security feature of the Android platform, you cannot, under any circumstance, have a foregrounded service without also having a notification. This is because a foregrounded service consumes a heavier amount of resources and is subject to different scheduling constraints (i.e., it doesn't get killed as quickly) than background services, and the user needs to know what's possibly eating their battery. So, don't do this.
However, it is possible to have a "fake" notification, i.e., you can make a transparent notification icon (iirc). This is extremely disingenuous to your users, and you have no reason to do it, other than killing their battery and thus creating malware.
Update: This was "fixed" on Android 7.1. https://code.google.com/p/android/issues/detail?id=213309
Since the 4.3 update, it's basically impossible to start a service with startForeground()
without showing a notification.
You can, however, hide the icon using official APIs... no need for a transparent icon: (Use NotificationCompat
to support older versions)
NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setPriority(Notification.PRIORITY_MIN);
I've made peace with the fact the notification itself still needs to be there but for who ever who still wants to hide it, I may have found a workaround for that as well:
startForeground()
with the notification and everything.startForeground()
(same notification ID)stopSelf()
and in onDestroy call stopForeground(true)
).Voilà! No notification at all and your second service keeps running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With