如何避免子类化 Android.App.Application

How to avoid subclassing Android.App.Application

过去我将 Application 子类化以维护应用程序的活动数据库连接。但是,根据 this SO answer Application runs in the UI thread, which makes me think I should definitely not use it for database access. Furthermore, according to the Xamarin Application docs(以及 Android 的那些):

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.ApplicationContext when first constructing the singleton.

我想我理解 Context 是我可以用来维护对应用程序资源的某种静态访问的东西,但文档中没有示例,我以前也没有遇到过这种情况。谁能解释上面的说明并说明他们如何使用 Context 来维护应用程序资源(除非我完全忽略了这一点)?链接或直接示例将不胜感激。

我相信我已经找到了我正在寻找的机器人答案。

Dave Smith 提供了 "static singleton" 的 simple example,如上面文档注释中所引用:

public class CustomManager {
    private static CustomManager sInstance;

    public static CustomManager getInstance(Context context) {
        if (sInstance == null) {
            //Always pass in the Application Context
            sInstance = new CustomManager(context.getApplicationContext());
        }

        return sInstance;
    }

    private Context mContext;

    private CustomManager(Context context) {
        mContext = context;
    }
}

Context 本身对 CustomManager 的寿命没有贡献 - 它的存在仅仅是由于静态单例本身的性质。 context.getApplicationContext() (Xamarin Context.ApplicationContext) 提供的 Context 只是在单例需要时访问应用程序 Context 的一种方式。

话虽这么说,正如 this SO question and its top two answers 所阐述的那样,真正的问题不是如果,而是您如何希望您的全局应用程序数据成为单例 - 作为框架提供的扩展 Application 单例,或者作为您创建的一个额外的、单独的单例,它可能会或可能不会使用前者。

就我而言,我想我已经满足于简单地 classing Application。直观地说,将应用程序数据存储在 Application class 的某些变体中更有意义。此外,我对一般情况下创建单例有一定的 OOP 疑虑,所以我觉得使用已经存在的单例比创建自己的单例更安全。这个单例由框架管理,所以虽然这不能保证安全,避免本质上归结为全局变量的典型问题(嘶嘶声),但至少它比我自己滚动要安全一些。

P.S。 - 回复:使用在 UI 线程中运行的 Application,似乎使用静态单例并没有给我任何额外的好处 - 再一次,因为这都是使用 Application 总计.我想我可能会遵循 here 提供的建议并使用 AsyncTasks 进行处理器繁重的操作。