如何正确初始化可以多次使用的firebase应用程序? [英] how to properly initialize firebase app that can be used more than once?

查看:52
本文介绍了如何正确初始化可以多次使用的firebase应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我会在活动中像这样初始化firebase

usually I initialize firebase in my activity just like this

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // usually initializing firebase just like this
        FirebaseApp.initializeApp(this)

}

但是现在我需要传递 firebaseApp 来获取 FirebaseStorage 实例,如下所示:

but now I need that firebaseApp to be passed to get FirebaseStorage instance like this:

    // set firebase option
    val optionBuilder = FirebaseOptions.Builder()
    optionBuilder.setStorageBucket("newBucket")
    val firebaseOption = optionBuilder.build()

    // initialize firebase app
    val app = FirebaseApp.initializeApp(this,firebaseOption)

    // create reference, pass app to firebase storage
    val storageRef = FirebaseStorage.getInstance(app).reference.child("profilePicture")

但是问题是.....

but the problem is.....

我需要在多个地方创建该Firebase存储参考.那么如何正确初始化firebase应用程序,以便可以在多个地方使用它?

I need to create that firebase storage reference in more than one place. so how how to properly initialize firebase app so that I can use it in more than one place ?

我是否需要在MainActivity 中初始化它,并在需要存储引用时再次重新创建它?这似乎是个坏主意,但我不知道....请帮助:)

do I need to initialize it in MainActivity AND recreate it again whenever I need to make storage reference ? it seems like a bad idea, but I don't know .... please help :)

推荐答案

只需将其初始化一次,然后将其存储在一个他们都可以访问的地方-单例.

Just initialize it once and store it in a place where they can all access it - a singleton.

这篇关于如何正确初始化可以多次使用的firebase应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆