首页 > 解决方案 > 如果失败,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

标签: androidkotlinobjectinitialization

解决方案


根据定义,单例只初始化一次——我认为你无论如何都不能重新初始化它们。您可以将其设置为普通类,而不是单例,并在已启用蓝牙时创建它。您也可以将其保留为单例,并且不在构造函数中执行初始化,而是按需执行。在大多数情况下,在构造函数中执行更高级的东西并不是一个好主意。

您还应该考虑在启用蓝牙时初始化服务然后用户禁用它的情况。


推荐阅读