You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase认证登录后应用崩溃(自动最小化)及Firestore配置异常解决

解决方案:Firestore设置调用时机错误导致的启动异常

问题根源

从日志可以明确,异常触发点是MainActivity.onCreate()第135行调用setFirestoreSettings(),但此时Firestore已经完成启动——因为你在LoginActivity中已经通过logsCollectionRef.document().set()执行了Firestore读写操作。Firestore的规则是必须在调用任何其他Firestore方法(如获取集合、读写数据)之前完成Settings配置,否则就会抛出该非法状态异常。

修复步骤

1. 将Firestore配置移到应用启动最早期

创建自定义Application类,在应用启动阶段就完成Firestore的Settings配置,确保这是第一个Firestore相关操作:

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化Firebase(若未自动初始化)
        FirebaseApp.initializeApp(this);
        
        // 配置Firestore Settings,这是第一个Firestore操作
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                // 添加你的自定义配置示例:
                // .setPersistenceEnabled(true)
                // .setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED)
                .build();
        db.setFirestoreSettings(settings);
    }
}

2. 在Manifest中指定自定义Application

打开AndroidManifest.xml,在<application>标签中添加android:name属性:

<application
    android:name=".MyApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.MyApp">
    <!-- 你的Activity声明 -->
</application>

3. 移除MainActivity中的重复配置

删除MainActivity.onCreate()中第135行的setFirestoreSettings()代码,避免重复触发配置冲突。

额外注意事项

  • 全局仅需配置一次Firestore Settings,不要在多个Activity中重复调用setFirestoreSettings()。
  • 若无需自定义Firestore配置,可直接删除所有setFirestoreSettings()调用,使用默认设置即可。
  • 确保所有Firestore读写操作、集合引用获取,都在Settings配置完成后执行。

内容的提问来源于stack exchange,提问作者XenLeaks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 09:47:03