具有全局上下文的 Android 单例

标签 android application-singleton

根据它所述的 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.getApplicationContext() when first constructing the singleton.

如何创建一个具有全局上下文的静态单例,以便它能够在我的应用程序中更改的正在运行的 Activity 中幸存下来?有一个引用 getApplicationContext() 的静态上下文就足够了吗?

最佳答案

对问题的另一个修改(2016 年)

最近(截至 2016 年及以后)我一直在做的事情是:

只需使用 Dagger 2。无论您在哪里需要 Context,您都可以:

@Inject Context context;

就是这样。在此期间,注入(inject)所有其他可能是单例的东西。

编辑/改进的答案(2014 年)

因为这个答案越来越受欢迎,我将使用我最近(截至 2014 年 7 月)使用的示例代码来改进我自己的答案。

首先让应用程序保持对自身的引用。

public class App extends Application {
   private static App instance;
   public static App get() { return instance; }

   @Override
   public void onCreate() {
      super.onCreate();
      instance = this;
   }
}

然后在任何需要访问 context 的单例上,我使用双重检查同步以线程安全的方式延迟加载单例,如此处所述 https://stackoverflow.com/a/11165926/906362

private static SingletonDemo instance;

public static SingletonDemo get() {
   if(instance == null) instance = getSync();
   return instance;
}

private static synchronized SingletonDemo getSync() {
   if(instance == null) instance = new SingletonDemo();
   return instance;
}

private SingletonDemo(){
   // here you can directly access the Application context calling
   App.get();
}

原答案

文档建议使用 normal singleton pattern

 public class SingletonDemo {
    private static SingletonDemo instance = null;

    private SingletonDemo() {       }

    public static SingletonDemo getInstance() {
            if (instance == null) {
                 instance = new SingletonDemo ();
            }
            return instance;
    }
}

并在其中包含这样的方法:

 private Context context;
 init(Context context){
    this.context = context.getApplicationContext();
 }

记得调用它来初始化单例。

Application 方法和 Singleton 方法之间的区别以及 Singleton 更好的原因在于文档 以更模块化的方式实现相同功能

关于具有全局上下文的 Android 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14057273/

相关文章:

java - 如何检查 fragment 在 Activity OnBackpressed 中是否可见

android - 如何以编程方式备份​​ SD 卡中的 sqlite 文件?

Play Framework:加载和使用常量字符串的最佳解决方案

Android:保存存储在应用程序单例类中的数据的最佳方式

ios - 用户信息。是否使用单例类?

android - 什么是 setDisplayOrientation() 的 Camera2 API 等效项?

android - 使用 XML 中的重力或 Linear_gravity 在 LinearLayout 中左对齐图像

android - ProgressDialogs 和 Material 设计规范