Should the initialization logic (e.g. for multiple singletones) be in OnCreate or OnResume?

Say I have singlets with mehods initialized for a general LocationController, BatteryController, AppSateController, etc.

Should they be in onResume, unlike OnCreate, since OnCreate is called at every turn, every time it changes to foregroud, etc. ??

+5
source share
2 answers

My recommendation, as a rule, is to implement singletones as usual. Ignore Android and just do the usual 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;
    }
}

Singleton.getInstance() . , . , ( ), , , , (, , ) . , , - .

, 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();
    }
}
+16

( , ), Application onCreate(). , , , Application.

+1

All Articles