如何在Jetpack撰写中动态跟踪BluetoothAdapter状态变化?



在我的应用程序中,我想知道用户是否使用状态栏启用/禁用蓝牙并显示相关的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函数内部初始化才能响应,这是我最初误解的地方。

  1. 定义一个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")
}
}
}
}
}
  1. @Composable函数内部,像往常一样使用此值:
@Composable
private fun MainScreen(
isBluetoothEnabled: MutableState<Boolean>
) {
if (isBluetoothEnabled) {
// Display some UI
} else {
// Display different UI
}
}

就是这样!

相关内容

  • 没有找到相关文章

最新更新