gpt4 book ai didi

android - 初始化逻辑(比如大量单例)应该在 OnCreate 还是 OnResume 中?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:54:31 25 4
gpt4 key购买 nike

假设我有一个带有通用 LocationController、BatteryController、AppSateController 等初始化方法的单例...

这些应该在 onResume 中而不是 OnCreate 中,因为 OnCreate 在每次旋转、每次更改为前景时都会被调用,等等...?

最佳答案

我的建议通常是像往常一样直接实现单例。忽略 Android,只做像这样的正常事情:

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()。您的单例将在此时被实例化,并且只要您的进程存在,就会继续被重复使用。这是一个很好的方法,因为它允许你的单例被延迟分配(只在需要时),而不是为你可能不需要的东西做一堆前期工作,这会导致你的启动(并因此响应用户)受苦。它还有助于保持您的代码更简洁,关于您的单例及其管理的所有内容都位于其自己的位置,并且不依赖于您正在运行的应用程序中的某个全局位置来对其进行初始化。

此外,如果您需要在单例中使用上下文:

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

关于android - 初始化逻辑(比如大量单例)应该在 OnCreate 还是 OnResume 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com