我正在尝试使用 Kotlin 将 Dialogflow(以前的 api.ai)代理与我的 Android 应用程序集成。我查看了关于 kotlin 的其他问答lateinit
,Android 中的 onCreate() 生命周期非常适合后期初始化实现,以避免在 Kotlin 中使用空对象和相应!!
的访问编写脏代码。?
但是我在尝试自定义类的实例时遇到了“ Property getter or setter expected ”的错误。lateinint
这是代码:
class AIApplication : Application() {
private var activitiesCount: Int = 0
var lateinit settingsManager: SettingsManager
//private set
private val isInForeground: Boolean
get() = activitiesCount > 0
override fun onCreate() {
super.onCreate()
settingsManager = SettingsManager(this)
}
这给了我“预期的属性获取器或设置器”的错误lateinit settingsManager
。这是SettingsManager
定义:
class SettingsManager(private val context: Context) {
private val prefs: SharedPreferences
private var useBluetooth: Boolean = false
var isUseBluetooth: Boolean
get() = useBluetooth
set(useBluetooth) {
this.useBluetooth = useBluetooth
prefs.edit().putBoolean(PREF_USE_BLUETOOTH, useBluetooth).commit()
val controller = (context.applicationContext as AIApplication).getBluetoothController()
if (useBluetooth) {
controller!!.start()
} else {
controller!!.stop()
}
}
init {
prefs = context.getSharedPreferences(SETTINGS_PREFS_NAME, Context.MODE_PRIVATE)
useBluetooth = prefs.getBoolean(PREF_USE_BLUETOOTH, true)
}
companion object {
private val SETTINGS_PREFS_NAME = "ai.api.APP_SETTINGS"
private val PREF_USE_BLUETOOTH = "USE_BLUETOOTH"
}
}
那么这样做的正确方法是什么?我需要对 SettingsManager 类进行一些更改吗?请清楚地解释整个概念。