Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should initialization logic (say for numerous singletons) be in OnCreate or OnResume?

Tags:

android

Say I have singletons with inilizations mehods for a generic LocationController, BatteryController, AppSateController,etc...

Should these be in onResume as opposed to OnCreate since OnCreate gets called on every rotate, every time it changes to foregroud, etc...?

like image 345
Samuel Elrod Avatar asked Feb 24 '13 05:02

Samuel Elrod


2 Answers

My recommendation is generally to implement singletons like you normally would directly. Ignore Android, and just do the normal kind of thing like this:

class Singleton {
    static Singleton sInstance;

    static Singleton getInstance() {
        // NOTE, not thread safe!  Use a lock if
        // this will be called from outside the main thread.
        if (sInstance == null) {
            sInstance = new Singleton();
        }
        return sInstance;
    }
}

Now call Singleton.getInstance() at the point you need it. Your singleton will be instantiated at that point, and continue to be re-used for as long as your process exists. This is a good approach because it allows your singletons to be lazily allocated (only as they are needed), rather than doing a bunch of up-front work for things you may not need right away which causes your launch (and thus responsiveness to the user) to suffer. It also helps keep your code cleaner, everything about your singleton and its management is located in its own place, and doesn't depend on some global place in your app being run to initialize it.

Also if you need a Context in your singleton:

class Singleton {
    private final Context mContext;

    static Singleton sInstance;

    static Singleton getInstance(Context context) {
        // NOTE, not thread safe!  Use a lock if
        // this will be called from outside the main thread.
        if (sInstance == null) {
            sInstance = new Singleton(context);
        }
        return sInstance;
    }

    private Singleton(Context context) {
        // Be sure to use the application context, since this
        // object will remain around for the lifetime of the
        // application process.
        mContext = context.getApplicationContext();
    }
}
like image 141
hackbod Avatar answered Oct 16 '22 16:10

hackbod


If You need initialize singletons (I assume application-level singletons), then appropriate way might be to extend Application and provide needed initialization in its onCreate() method. However, if initialization is heavy it might be a good idea to place it in separate thread, which get started from Application class.

like image 35
sandrstar Avatar answered Oct 16 '22 16:10

sandrstar