如何检查 Firebase 应用程序是否已经在 Android 上初始化

使用以下命令,第一次调用它时可以工作,但是随后的调用失败,并且“ FirebaseApp name [ DEFAULT ]已经存在!”

public FirebaseDatabase conn(Context c) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setApiKey("key")
.setDatabaseUrl("url")
.setApplicationId("ID")
.build();




/////I tried Try and Catch with no success//////
FirebaseApp app = FirebaseApp.initializeApp(c, options);


/// for this : FirebaseApp app = FirebaseApp.initializeApp(c, options, "some_app");
//// will fail with "FirebaseApp name some_app already exists!"
return FirebaseDatabase.getInstance(app);
}

以上所有都是连接到第二个 Firebase 应用程序的尝试。

87021 次浏览

I think what you want to do is check the list of running apps before initializing your app. Each of the SDKs have a method for getting this array, in android it's getApps:

https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseApp.html

Then you can check to see if your app is already initialized.

In my case I just ended up checking the length of the array (I'm using the javascript / web sdk so I'm sure it's a little different for Android) and initializing a new app if it is 0.

On firebase web, you check if already initialized with:

if (firebase.apps.length === 0) {
firebase.initializeApp({});
}

I faced the similar issue, I resolved it as following:

  1. Create a var for the application and initialize it with null
  2. Take reference of the application while initialization
  3. Check before initializing it again

//global variable
var firebaseResumeDownloadAdd = null;


//inside function check before initializing
if(firebaseResumeDownloadAdd==null){
firebaseResumeDownloadAdd =
firebase.initializeApp(functions.config().firebase);
}

I faced the similar issue. I solved the following problem by deleting the already initialized app.

    // Access your firebase app
let app = firebase.app();
// Delete your app.
app.delete(app);

Solution works for web.

You can try to get the Firebase app instance, in it's code firebase checks if it's initialized, if not it throws an IllegalStateException.

    try{
FirebaseApp.getInstance();
}
catch (IllegalStateException e)
{
//Firebase not initialized automatically, do it manually
FirebaseApp.initializeApp(this);
}

For those wondering how to do the same as the accepted answer, in Android:

if (FirebaseApp.getApps(context).isEmpty()) {
FirebaseApp.initializeApp(context);
}

and in an instrumented test environment, use this context:

InstrumentationRegistry.getContext()

Not sure in android, but how about using a singleton method. In JS you can do this. Hope this helps someone

// Config file
import * as firebase from "firebase";


const config = {...};


export default !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();


// Other file
import firebase from '../firebase';

If you are using Nativescript to build an hybrid mobile app for Android | iOS you can use this script:

import * as firebase from 'nativescript-plugin-firebase';


_initFirebase(): Promise<any> {
if (!(firebase as any).initialized) {
return firebase.init({}).then(
() => {
console.info('firebase started...');
},
(error) => console.error(error)
);
}
}




import * as firebase from "firebase/app";
firebase.apps.map(e => e.name); // Give you an array of initialized apps

in Android, depending on Daniel Laurindo's answer:

if (FirebaseApp.getApps(context).size != 0) {


}

In v9, Firebase has been modularized for better tree shaking. So we can no longer import entire app and check the apps property AFAIK. The below approach can be used instead.

import { initializeApp, getApps, getApp } from "firebase/app";
getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();

https://firebase.google.com/docs/reference/js/v9/app.md#getapps for documentation

In firebase admin SDK for java, initialize the app if and only if there is no app.

if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp();
}

A cleaner solution for ES6+ is


if (!firebase.apps.length) {
...
}

Firebase Version 9

import { initializeApp, getApp } from "firebase/app";


const createFirebaseApp = (config = {}) => {
try {
return getApp();
} catch () {
return initializeApp(config);
}
};


const firebaseApp = createFirebaseApp({/* your config */})

Simple use Java 8 Stream and Optional featured.

Code below as

FirebaseApp.getApps()
.stream()
.filter(firebaseApp ->
firebaseApp.getName().equals("APP_NAME"))
.findFirst()
.orElseGet(() -> FirebaseApp.initializeApp(firebaseOptions, "APP_NAME"));

For those who are using dotNet FirebaseAdmin SDK

if (FirebaseApp.GetInstance("[DEFAULT]") == null)
{
var createdApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("private-key.json")
});
}

Th Use Platform check to initialize according to environment

On firebase web, you check if already initialized with

use the below snippet while launching MYAPP()

import 'dart:io';


void main() async {

WidgetsFlutterBinding.ensureInitialized();

if (Platform.isAndroid || Platform.isIOS) {

await Firebase.initializeApp();

} else {

if (Firebase.apps.isEmpty) {


await Firebase.initializeApp(


// connect for web to firebase
options:firebaseOptions


}

} runApp(const MyApp());

}

const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();