在我的应用程序中,我想知道用户是否使用状态栏启用/禁用蓝牙并显示相关的UI。为此,我认为我需要在@Composable
函数中跟踪当前的BluetoothAdapter.isEnabled
状态。这是我的文件:
class MainActivity : ComponentActivity() {
private val bluetoothAdapter: BluetoothAdapter by lazy {
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothManager.adapter
}
override fun onCreate(savedInstanceState: Bundle?) {
var isBluetoothEnabled = bluetoothAdapter.isEnabled
setContent {
AppTheme {
MainScreen(isBluetoothEnabled)
}
}
}
}
@Composable
private fun MainScreen(
isBluetoothEnabled: Boolean
) {
if (isBluetoothEnabled) {
// Display some UI
} else {
// Display different UI
}
}
当应用程序启动时,我可以为应用程序获得蓝牙的正确状态,但由于BluetoothAdapter.isEnabled
不是@Composable
生命周期的一部分,因此我无法跟踪它并对变化做出反应,就像它是一个反应状态一样。有什么方法可以达到我想要的行为吗?
我能够通过使用mutableStateOf
来解决这个问题。它不需要在@Composable
函数内部初始化才能响应,这是我最初误解的地方。
- 定义一个
mutableStateOf
值和一个BroadcastReceiver
来跟踪BluetoothAdapter
的状态。当蓝牙状态改变时,更新该值。
private var isBluetoothEnabled = mutableStateOf(false)
private val mReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == BluetoothAdapter.ACTION_STATE_CHANGED) {
when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
BluetoothAdapter.STATE_OFF -> {
isBluetoothEnabled.value = false
Log.i("Bluetooth", "State OFF")
}
BluetoothAdapter.STATE_ON -> {
isBluetoothEnabled.value = true
Log.i("Bluetooth", "State ON")
}
}
}
}
}
- 在
@Composable
函数内部,像往常一样使用此值:
@Composable
private fun MainScreen(
isBluetoothEnabled: MutableState<Boolean>
) {
if (isBluetoothEnabled) {
// Display some UI
} else {
// Display different UI
}
}
就是这样!