Search code examples
androidandroid-service

Is a Singleton instance initiated from inside an Android service going to work as Service?


I have a Singleton structure on my Android application that is used to share Data among different classes:

public class DataHandler {

    public DataHandler() {

    }

    private static DataHandler instance = null;

    public static DataHandler getInstance() {
        if (instance == null) {
            instance = new DataHandler();
        }
        return instance;
    }

}

I know that even though this Singleton instance is static, the Android is going to kill it after a time that my application runs on background (for memory management reasons). I also know that services on Android can run on background for an undetermined amount of time. Considering that the static instance of the singleton is created when we first call a method from it, my doubt is: Is the instance of a Singleton class that was first initiated from inside a Service class going to work as a Service on an application? (and not be killed by the Android when my app is running on background)


Solution

  • No. When your app is killed, it is killed. All of the parts of it are killed.

    In older versions of Android, the OS was aware that you were running a Service and that made it less likely to kill you application (just as when one of your app's Activities is currently visible, it is very unlikely to be killed). It only works, though, as long as the Service (Activity) is running.

    Modern Android has a lot more memory to play around with and apps can run for a very long time (days), even when they are neither running a Service nor a visible Activity. You can't count on in-memory data, though. If you need it, persist it.