I am trying to make my Service
running in foreground. I tried to use this example (please look for the section "Running a Service in the Foreground"), but startForeground()
does not actually show my notification. And no exceptions is thrown. To make it shown, I need to use NotificationManager
like here explained. With NotificationManager
my notification works, but i'm not sure that my Service
is foreground after this "silent" call to startForeground()
.
What can be wrong?
EDIT: I just tested this sample project that should demonstrate startForeground()
, but it does not work! I use API v7.0, I tested it both on emulator and real device (SE Xperia Neo). Notification does not appear.
EDIT2: if i try to call setForeground()
then i got a warning setForeground: ignoring old API call
.
I also tried to use startForegroundCompat()
as described here, but effect is absolutelly the same. I check if my service is foreground using ActivityManager.RunningServiceInfo
as described here, and I see that my service is not foreground.
As a security feature of the Android platform, you cannot, under any circumstance, have a foregrounded service without also having a notification.
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.
Foreground services are an advanced Android concept which allows you to display notifications to your users when running long lived background tasks. The notification acts like any other notification, however it cannot be removed by the user and lives for the duration of the service.
I just noticed that startForeground()
doesn't show the notification icon if the id
parameter is set to 0
...
startForeground(0, notification); // Doesn't work... startForeground(1, notification); // Works!!!
I hope that it could help someone stuck on this.
in addition to the best answer. you should also check that have you called setSmallIcon
. On my android phone, I cannot get what I expected without calling setSmallIcon
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