从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
相关产品推荐
相关产品推荐

