The preservation of services in Android has always been a topic of discussion. This article does not explore preservation, but rather what to pay attention to when a Service is killed and then restarted. To make the application less likely to be killed, we use the foreground service and return STICK_KEY on onStartComment.

The death of the front desk Service

Develop A small application, using A foreground service, the application is called A application, the foreground service is called BService. After the application is installed on the device, the front desk service starts, press the power button, and the screen stops. (a 3G device running Android9). In the dead of night, the device senses it is running low on memory and starts killing applications. App A was also taken care of and killed. But application A opened the foreground service and returned STICK_KEY, humbly leaving A message asking the device to revive it once more, if it had enough memory.

The Service of rebirth

After the end time, the device finds that the memory is sufficient, remembers the request of application A’s BService, and revives the BService. As soon as BService comes back to life, it’s ready to go again, the background is connected, the broadcast is registered, and it’s ready to pick up where it left off. The BService uses multiple static objects to save what it did before, and when it resurrects it plans to read those objects, and then… BService found what was gone! BService forgets all the work it did before and has to do everything from scratch.

conclusion

When a Service is killed by the system, its entire application is killed and its memory is reclaimed, and when a Service is recreated by AMS, the entire application is recreated. So, everything that was previously in the application static variables or anything else is completely gone. Therefore, Service development should always be careful to maintain its independence and try not to hold variables created in other components, which will be null if the application is killed