英文:
How to hold return until DEVICE_DISCOVERY_FINISHED in adnroid
问题
以下是您要翻译的内容:
"Hi i am quite new to android development and using some native code in flutter. So i have called this function to scan bluetooth devices in MainActivity.kt.
private fun scanBluetooth(): Set<String> {
var foundDevices = mutableSetOf<String>()
var isFinished = false
val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
bluetoothAdapter?.startDiscovery()
var filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String = intent.action
when(action) {
BluetoothDevice.ACTION_FOUND -> {
val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
val rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE)
foundDevices.add("${deviceHardwareAddress} ${rssi}")
}
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
isFinished = true;
}
}
}
}
registerReceiver(receiver, filter)
return foundDevices
}
So i want to return foundDevices only when BluetoothAdapter.ACTION_DISCOVERY_FINISHED is finished. Can you suggest a way how to achieve this?
android
I have tried something like this but getting errors.
return when (isFinished) {
true -> {
unregisterReceiver(receiver)
return foundDevices
}
}"
请注意,我只翻译了您的请求部分,不包括代码部分。如果您有任何其他问题,请随时提出。
英文:
Hi i am quite new to android development and using some native code in flutter. So i have called this function to scan bluetooth devices in MainActivity.kt.
private fun scanBluetooth(): Set<String> {
var foundDevices = mutableSetOf<String>()
var isFinished = false
val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
bluetoothAdapter?.startDiscovery()
var filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String = intent.action
when(action) {
BluetoothDevice.ACTION_FOUND -> {
val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
val rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE)
foundDevices.add("${deviceHardwareAddress} ${rssi}")
}
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
isFinished = true;
}
}
}
}
registerReceiver(receiver, filter)
return foundDevices
}
So i want to return foundDevices only when BluetoothAdapter.ACTION_DISCOVERY_FINISHED is finished. Can you suggest a way how to achieve this?
android
I have tried something like this but getting errors.
return when (isFinished) {
true -> {
unregisterReceiver(receiver)
return foundDevices
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论