如果初始化逻辑(说为众多单身)在OnCreate中或OnResume? [英] Should initialization logic (say for numerous singletons) be in OnCreate or OnResume?

查看:168
本文介绍了如果初始化逻辑(说为众多单身)在OnCreate中或OnResume?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有单身人士inilizations mehods一个通用LocationController,BatteryController,AppSateController,等等...

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

如果这些在onResume,而不是因为OnCreate中来OnCreate中被调用的每一个旋转,每次更改为foregroud时间,等...?

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

推荐答案

我的建议一般是通常直接实现像你单身会。忽略Android的,只是做了正常的那种事情是这样的:

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;
    }
}

现在,在你需要它的地方调用Singleton.getInstance()。您的单将在该点被实例化,并不断被重复使用,只要你的进程是否存在。这是一个很好的方法,因为它可以让你的单身被懒洋洋地分配(仅在需要时),而不是做了一堆前期工作的事情,你可能不需要马上引起你的启动(从而反应到用户)受到影响。这也有助于保持你的code清洁,一切关于你的单身及其管理位于自己的一席之地,并且不依赖于一些全球性的地方在你的应用程序正在运行进行初始化。

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.

另外,如果你需要一个Context在单:

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

这篇关于如果初始化逻辑(说为众多单身)在OnCreate中或OnResume?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆