startForeground() does not show my Notification

2019-01-17 14:24发布

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.

6条回答
相关推荐>>
2楼-- · 2019-01-17 14:28

DMitry. I have just suffered your problem and found the cause.

If your app is changing state of a COMPONENT PackageManager.setComponentEnabledSetting()) Android removes the service from foregraound and its notification icon.

Bug reported at Nov, 2011

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-17 14:33

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-17 14:40

This might be an old thread, but I'd like to add what I just learned which is not mentioned yet:

It is possible that a Service is still alive after stopSelf() is called because there are Activity that have bound to the Service. As a matter of fact, the startForeground() is just not going to show the notification nor giving any exception in this circumstance.

查看更多
The star\"
5楼-- · 2019-01-17 14:43

Is your service a started service or a bound service? I had the same issue with a bound service, but starting the service before binding it allowed me to call startForeground(int, notification) with and have the notification show up.

查看更多
ら.Afraid
6楼-- · 2019-01-17 14:45

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

查看更多
贼婆χ
7楼-- · 2019-01-17 14:50

in my case there was no notification after startForeground(...) invoke because I used only .setSubText(...) for setting the message of it (because it is rendered with smaller font on most of devices). But some of devices Xiaomi Redmi Note 4 won't show any notification if You not set message by using .setContentText(...).

Hope that will help someone

查看更多
登录 后发表回答