android12 bluetoothGatt相关使用

325 阅读1分钟

1.连接

@SuppressLint("MissingPermission")
fun connectGatt(context: Context,address:String ,mGattCallback:BluetoothGattCallback)
    :BluetoothGatt?{
    initBluetoothAdapter(context)
    var gatt :BluetoothGatt?= null
    if (mBluetoothAdapter?.isEnabled == true){
        val device = mBluetoothAdapter?.getRemoteDevice(address);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            gatt = device?.connectGatt(
                context, false, mGattCallback,
                BluetoothDevice.TRANSPORT_LE,
                BluetoothDevice.PHY_LE_1M_MASK or BluetoothDevice.PHY_LE_2M_MASK
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            gatt = device?.connectGatt(
                context, false, mGattCallback,
                BluetoothDevice.TRANSPORT_LE
            )
        } else {
            gatt = device?.connectGatt(context, false, mGattCallback)
        }
    }

    return gatt
}

2.设置回调

object :BluetoothGattCallback()

3.发现服务和特征值

override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
    super.onConnectionStateChange(gatt, status, newState)
    if (status == BluetoothGatt.GATT_SUCCESS){
        if (newState == BluetoothGatt.STATE_CONNECTED){
            if (gatt == null) {
                showToast(ctx,"YY-HID gatt已连接,但是gatt是null!!")
                return
            }

            SystemClock.sleep(2000)
            Log.d(TAG,"YY-HID gatt已连接,准备执行 gatt.discoverServices()")
            // 发现远程设备提供的服务及其特征和描述符。
            gatt.discoverServices()

        }else{
            showToast(ctx,"YY-HID gatt连接异常 newState ->$newState")
        }
    }else{
        if (newState == BluetoothGatt.STATE_DISCONNECTED) {
            showToast(ctx,"YY-HID gatt连接失败 STATE_DISCONNECTED")
        }else{
            showToast(ctx,"YY-HID gatt连接失败 newState ->$newState")
        }
    }

}

4.读取信息

override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
    super.onServicesDiscovered(gatt, status)
    if (gatt == null) {
        showToast(ctx,"YY-HID gatt已发现服务和特征值,但是gatt是null!!")
        return
    }
    showToast(ctx,"YY-HID gatt已发现服务和特征值,准备 writeOpCode1()")
    MyDfuUtil.instance.writeOpCode1(gatt)

}