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

从Firebase Remote Config设置BuildConfigField值遇赋值错误求助

解决Firebase Remote Config赋值BuildConfigField时的"val cannot be reassigned"错误

错误原因

BuildConfig中的字段是编译时生成的只读常量(val),APK编译完成后其值就固定了,运行时无法修改。你试图在运行时给BuildConfig.enableMaintenceMood赋值,这违背了它的只读特性,因此触发错误。

正确实现方式

方案1:维护运行时全局变量

在Application类或单例类中定义一个可变变量,存储从RemoteConfig获取到的最新值,业务逻辑直接使用该变量:

class MyApp : Application() {
    companion object {
        // 初始化值用BuildConfig的默认值
        var enableMaintenanceMode = BuildConfig.enableMaintenceMood
    }

    override fun onCreate() {
        super.onCreate()
        initRemoteConfig()
    }

    private fun initRemoteConfig() {
        val remoteConfig = Firebase.remoteConfig
        val configSettings = FirebaseRemoteConfigSettings.Builder()
            .setMinimumFetchIntervalInSeconds(60)
            .build()
        remoteConfig.setConfigSettingsAsync(configSettings)

        remoteConfig.setDefaultsAsync(mapOf("enableMaintenceMood" to BuildConfig.enableMaintenceMood))

        remoteConfig.fetchAndActivate().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val remoteValue = remoteConfig.getBoolean("enableMaintenceMood")
                // 更新全局变量
                MyApp.enableMaintenanceMode = remoteValue
                // 这里可以执行维护模式相关逻辑,比如跳转页面
            } else {
                Toast.makeText(this, "配置获取失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

后续业务代码中直接使用:

if (MyApp.enableMaintenanceMode) {
    // 进入维护模式逻辑
}

方案2:直接读取RemoteConfig缓存值

fetchAndActivate成功后,RemoteConfig会缓存最新值,后续需要判断时直接读取即可,无需额外存储:

// 需要判断维护模式的地方
val isMaintenanceMode = Firebase.remoteConfig.getBoolean("enableMaintenceMood")
if (isMaintenanceMode) {
    // 执行维护模式逻辑
}

额外提示

注意变量名拼写错误:enableMaintenceMood应为enableMaintenanceMode,建议修正BuildConfig和RemoteConfig中的键名,避免后续出现拼写问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:05:12