如果失败,Kotlin 对象需要 init 再次发生
Kotlin object require init to happen again if failed
我有一个 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?
根据定义,单例只初始化一次 - 我认为您无法以任何方式重新初始化它们。您可以将其设为常规 class,而不是单例,并在蓝牙已启用时创建它。您也可以将其保持为单例,并且不在构造函数中执行初始化,而是按需执行。在大多数情况下,在构造函数中执行更高级的东西并不是一个好主意。
您还应该考虑以下情况:您在启用蓝牙时初始化服务,然后用户将其禁用。
我有一个 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?
根据定义,单例只初始化一次 - 我认为您无法以任何方式重新初始化它们。您可以将其设为常规 class,而不是单例,并在蓝牙已启用时创建它。您也可以将其保持为单例,并且不在构造函数中执行初始化,而是按需执行。在大多数情况下,在构造函数中执行更高级的东西并不是一个好主意。
您还应该考虑以下情况:您在启用蓝牙时初始化服务,然后用户将其禁用。