MyoBleFinder

com.roumai.myodecoder.device.ble.MyoBleFinder

Overview

MyoBleFinder 用于搜索附近的 MyoDecoder 设备。它提供了以下功能:

Constructors

#constructor/1

构造器,一般用于 APP 初始化时,需要加载蓝牙相关服务时构造该实例.

参数类型描述
autoConnectBoolean是否自动连接设备
val finder = MyoBleFinder(true)

Functions

#isBluetoothEnabled/0

判断蓝牙是否开启.

val bleOpen = finder.isBluetoothEnabled()
if (bleOpen.not()) {
    // 蓝牙未开启
    Log.i(TAG, "蓝牙未启用,请启用蓝牙")
}

#scan/1

搜索目标设备.

参数类型描述
callbackOnFinderUpdate监听搜索开始、结束、发现设备后的回调
val devices = ArrayList<Pair<String, BleDevice>>()
finder.scan(object : MyoBleFinder.OnFinderUpdate {
        override fun onStart() {
            devices.clear()
            Log.i(TAG, "scanning...")
        }

        override fun onFound(peripheral: BleDevice) {
            devices.add(peripheral.mac to peripheral)
        }

        override fun onStop(peripherals: List<BleDevice>) {
            Log.i(TAG, "scan stop")
            // print devices
            devices.forEach {
                Log.i(TAG, "device[${it.first}]: ${it.second}")
            }
        }
    }
)

#stop/0

停止搜索.

finder.stop()

Advanced Example

以下是一个使用 MyoBleFinder 搜索并展示出搜索到的设备的例子:

@Composable
fun DeviceList(finder: MyoBleFinder) {

    val devices = remember { mutableListOf<Pair<String, BleDevice>>() }

    val startScan = {
      finder.scan(object : MyoBleFinder.OnFinderUpdate {
              override fun onStart() {
                  devices.clear()
                  Log.i(TAG, "scanning...")
              }

              override fun onFound(peripheral: BleDevice) {
                  devices.add(peripheral.mac to peripheral)
              }

              override fun onStop(peripherals: List<BleDevice>) {
                  Log.i(TAG, "scan stop")
                  // print devices
                  devices.forEach {
                      Log.i(TAG, "device[${it.first}]: ${it.second}")
                  }
              }
          }
      )
    }

    Column {
        Button(onClick = { startScan() }) {
            Text("Start Scan")
        }
        Button(onClick = { finder.stop() }) {
            Text("Stop Scan")
        }
        devices.map { device ->
            Row {
                Text("device[${device.first}]: ${device.second}")
            }
        }
    }
}

@Composable
fun Main() {
    val finder = MyoBleFinder(true)
    Box {
        DeviceList(finder = finder)
    }
}

FQA

  • Q: 如何获取设备的 MAC 地址?

    A: device.mac 即为设备的 MAC 地址。MyoDecoder 设备都有其独一无二的 MAC 地址,格式为 XX:XX:XX:XX:XX:XX,比如 00:11:22:33:44:55