如何在整个Android应用中使用单个Firestore实例?

我尝试在整个应用程序中使用单个Firestore实例,因为随着Firebase的冷启动,第一个查询或要提取的第一个数据需要花费一段时间(例如2000ms-3000ms)。我尝试在扩展Application的类中将Firestore对象作为静态对象,但显示了Lint警告:“请勿将Android上下文类放在静态字段中;这是内存泄漏”。我不知道从这里去哪里。请帮我。

评论
Dora
Dora

getInstance() will get you an unique instance throught your whole app, when you use

FirebaseFirestore.getInstance()

要么

FirebaseDatabase.getInstance()

如果您要在不同的类中创建实例,它将不会创建另一个实例,而是会重复使用同一实例。

You can also see the implementation by ctrl + click on the method in your IDE

@NonNull
  public static FirebaseFirestore getInstance() {
    FirebaseApp app = FirebaseApp.getInstance();
    if (app == null) {
      throw new IllegalStateException("You must call FirebaseApp.initializeApp first.");
    } else {
      return getInstance(app, "(default)");
    }
  }




@NonNull
  public static FirebaseApp getInstance() {
    synchronized(LOCK) {
      FirebaseApp defaultApp = (FirebaseApp)INSTANCES.get("[DEFAULT]");
      if (defaultApp == null) {
        throw new IllegalStateException("Default FirebaseApp is not initialized in this process " + ProcessUtils.getMyProcessName() + ". Make sure to call FirebaseApp.initializeApp(Context) first.");
      } else {
        return defaultApp;
      }
    }
  }
点赞
评论