Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Singleton Instance vs Service

Here I want to ask one basic question which I couldn't find the answer while iam doing code.

As I understand, creating a singleton instance in application onCreate() is having less vulnerable than android service. In my application, i want to listen for location update which should have less likelihood to get destroyed. If I keep service it might get killed in low memory but still, the application can run in the background which would keep the instance. So I would like to go with singleton instance rather than service.

Is it a right approach?

like image 990
sd33din90 Avatar asked Feb 05 '23 20:02

sd33din90


1 Answers

Android can (and will) kill background processes in low resource situations, and also sometimes just because it wants to (especially on low-end devices in order to conserve battery and memory resources). It does this by killing the OS process hosting your application. In this case, your app will no longer be running in the background and therefore any singleton you may have created in Application.onCreate() will also be gone.

Android knowns nothing about your singleton and therefore has no reason to restore it.

However, if you create a Service and that Service returns START_STICKY from onStartCommand(), this tells Android that your Service wants to remain running all the time (if possible). In this case, if Android kills the OS process hosting your Service (due to resource constraints, or just because it wants to), Android will then automatically restart your Service (because Android knows about your Service and knows that it wants to run all the time). This is the correct way to do this.

NOTE: There are some devices (notably Chinese devices like Xiaomi, also Huawei, LG, Lenovo and others) that do not automatically restart STICKY services. These devices maintain a list of "protected apps" or "priviledged apps" that are allowed to run in the background and Android will only restart STICKY services for applications that are in this list. You will need to get your user to add your app to this list by hand. There is no way to programatically add your app to this list on these devices.

See https://stackoverflow.com/a/42120277/769265 and https://stackoverflow.com/a/41369032/769265

like image 194
David Wasser Avatar answered Feb 20 '23 12:02

David Wasser