How to prevent android service getting killed (Service with notification)

前端 未结 4 1301
太阳男子
太阳男子 2021-01-22 23:15

I am working on an application which need to show notification constantly.
I\'ve a service to show the notification every seconds.
When the resources goes low android is

相关标签:
4条回答
  • 2021-01-22 23:48

    Update:

    You can use Foreground Service in the scenario. From the docs:

    A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.


    In my knowledge there is no bulletproof way of preventing your service from being stopped by the android system. If the device is critical on memory/resources then your service has to be stopped for GC. This is also not recommended because your service will drain the device battery.

    0 讨论(0)
  • 2021-01-22 23:49

    As written above you need to use startForeground(int,Notification) method to aware user about your service. It also get more privilage for it.

    You can read more about it here (example inside).

    0 讨论(0)
  • 2021-01-23 00:00

    There is no way to completely stop it from ever being killed. Making it a foreground service helps. Returning start_sticky means it will be restarted if it is stopped (so it should do a startService on itself in its onCreate to make sure it restarts and not just gets recreated). But Android has the right to kill any service at any time due to resources.

    0 讨论(0)
  • 2021-01-23 00:05

    Use

    startForeground(int,Notification);
    

    in onCreate of service. It requires a notification number and a notification object which it will display in the notification bar.

    To remove the notification, use

    startForeground(0,Notification);
    
    0 讨论(0)
提交回复
热议问题