Search code examples
androidservice

Android service stopping unexpectedly


I have a service that also contains an activity the problem is sometimes it gets shut down by the operating system.

How can I prevent that from happening?


Solution

  • Not sure what you mean by "service that contains an activity".

    The OS can and will shut down services based on demand for memory. How often this happens depends on what you have running on your device, and the amount of memory that your device has.

    To try to minimize this, you can call Service.startForeground(). Please read the javadocs for the proper usage, and please look at stopForeground() as well.

    Note that this is still no guarantee. You must author your app to gracefully handle when your service is destroyed. Please read up on the Service lifecycle to understand how to handle this.

    Even if you could keep your service running at all times, it would be a bad idea. This is not a personal computer plugged in to AC power. A service that is perpetually running will greatly effect the battery life of the device.