我正在尝试在Android应用程序中设置Firebase消息传递,据我所知,我需要在对Firebase类执行任何其他操作之前运行FirebaseApp.initializeApp(context)
。我遇到的问题是我在尝试使用FirebaseInstanceId.getInstance().getInstanceId()
获取设备令牌之前正在运行initializeApp
,但 firebase 仍然抛出此错误:
09-05 11:16:20.314 24640-24640/com.company.AppName E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.company.AppName, PID: 24640
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.company.AppName/com.company.AppName.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.company.AppName. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.company.AppName. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@16.0.1:219)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source:1)
at com.company.AppName.MainActivity.onCreate(MainActivity.java:48)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
以下是初始化 firebase 并抛出错误的代码(以MainActivity.java
onCreate
为单位(:
FirebaseApp.initializeApp(this);
NativeApp
.shared()
.setContext(this)
.setDeviceToken(FirebaseInstanceId.getInstance().getInstanceId().toString());
如果我注释掉setDeviceToken
行,则不会抛出任何错误。initializeApp
异步的吗?Firebase Android设置指南甚至没有提到initializeApp
。
如果您使用记录的过程执行了与 Firebase 的集成,则无需调用 initializeApp。 如果您执行标准集成,Firebase 将在应用启动时自动初始化。 请在 FirebaseApp 的 API 文档中阅读有关此内容的更多信息。
如果您没有执行标准集成,那么您可以根据自己的使用案例在正确的时间调用 initializeApp。