android - 如果失败,Kotlin 对象需要再次发生 init
问题描述
我有一个对象 BleClient,它是单例的,负责我的所有 BLE 操作。
当我按预期从 BleClient 运行任何函数时,init 的调用方式如下:
init {
RLog.d(TAG_BLE, "BleClient init")
val bluetoothManager = MyApp.application.getSystemService(BluetoothManager::class.java)
bluetoothAdapter = bluetoothManager?.adapter
bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!
}
但是,当 BT 被禁用时,该函数的 init 会崩溃:
bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!
所以,我确实喜欢这样:
init {
RLog.d(TAG_BLE, "BleClient init")
val bluetoothManager = MyApp.application.getSystemService(BluetoothManager::class.java)
bluetoothAdapter = bluetoothManager?.adapter
//Check if adapter is enabled
if (bluetoothAdapter != null && bluetoothAdapter!!.isEnabled)
bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!
}
这可行,但是...在第一次失败后,用户打开 BT,然后从 BleClient 调用任何其他函数。init 将再次被调用,我需要它......
所以我做了:
init {
RLog.d(TAG_BLE, "BleClient init")
val bluetoothManager =
MyApp.application.getSystemService(BluetoothManager::class.java)
bluetoothAdapter = bluetoothManager?.adapter
require(bluetoothAdapter != null && bluetoothAdapter!!.isEnabled)
bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner!!
}
因为我需要这个初始化要求,如果它失败了,初始化应该再次触发。
但是我遇到了崩溃“原因:java.lang.IllegalArgumentException:要求失败。”
如何正确使用require?
解决方案
根据定义,单例只初始化一次——我认为你无论如何都不能重新初始化它们。您可以将其设置为普通类,而不是单例,并在已启用蓝牙时创建它。您也可以将其保留为单例,并且不在构造函数中执行初始化,而是按需执行。在大多数情况下,在构造函数中执行更高级的东西并不是一个好主意。
您还应该考虑在启用蓝牙时初始化服务然后用户禁用它的情况。
推荐阅读
- python - VSCode,你如何导入另一个文件中的函数?我得到一个 ImportError
- python - Python Selenium 在没有 driver.refresh() 的情况下查询页面元素
- c - 将字符串拆分为不同的部分,没有空格和分隔符
- python - 日期/月份计算
- python - TensorFlow - TFRecords 加载和转换带有边界框的图像
- amazon-web-services - AWS CLI 无法向 API Gateway 阶段变量添加权限
- javascript - 图像旁边的定位按钮
- blazor-webassembly - Blazor Webassembly 应用程序如何知道哪个用户已登录服务器端?
- kubernetes - 数据未跨容器共享
- python - 似乎不明白错误的原因