P_King P_King - 22 days ago 4x
Android Question

Application class lifecycle while service is running

I am developing an application with custom Application class which initializes a couple of singletons so they live during all application working time. I also have a couple of services in my application which work with these singletons. Is it possible situation that Application class will be destroyed by android with singletons' instances before services so services will not be able to use them? Or application lives always even for services of it's context? What is the best way to find a way out of this situation?


  • Regarding the application object:

The application object is the main absolute starting point on any Android app. It will always exist before any of the Manifest declared items such as Activity, Service and BroadcastReceiver. So relax that the singletons will be there for you.

  • Regarding the singleton paradigma:

That's a big discussion topic, you can google more about it so what follows is my personal opinion on it. Whatever is the reason for your singletons (a database, an bitmap caching, a FileUtils) I think it's ok and correct to initialise them on the very first point of entry of your app, which is the Application. But the application itself is not an object meant to carry or hold those objects, that way my suggested design approach is to:

=> on your singleton object/class you'll have to:

private static MySingletonClass instance; // reference to the single object
private MySingletonClass(Context c){ // private constructor to avoid construction from anywhere else
    // let's say it needs the context for construction because it's a database singleton
public static MySingletonClass get(){ // 
    if(instance == null) throw new RuntimeException("This singleton must be initialised before anything else");
    return instance;
public static void init(Context c){ // call the initialisation from the Application
   instance = new MySingletonClass(c);

=> and then on your Application object you simply init the singleton


with that way you'll keep the necessary initialisation, enforce the singleton pattern but to access the object you call to that object class not to the application. I know it's just a organisational difference, but I believe that that's what separate good and bad code.

So for example on your service the call is: MySingletonClass.get() and should never be MyApplication.mySingle.

hope it helps.