Android 蓝牙开发入坑及解决办法汇总

1、代码解除绑定

直接找不到removeBond方法,通过Method来调用。亲测可用

Method method= null;
try {
    method = bluetoothGatt().getDevice().getClass().getMethod("removeBond",(Class[])null );
} catch (NoSuchMethodException e) {
    throw new RuntimeException(e);
}
try {
    method.invoke(bluetoothGatt().getDevice(),(Object[]) null);
} catch (IllegalAccessException e) {
    throw new RuntimeException(e);
} catch (InvocationTargetException e) {
    throw new RuntimeException(e);
}

2、写入数据是会发现修改了MTU也没用,查看后台提示信息发现提示如下:

Skipped 1012 frames!  The application may be doing too much work on its main thread.

这是由于未清除缓存造成字节流太大,发送失败或者是蓝牙未正确接收到信息,此时需要清除缓存 ,一种方法是直接关闭手机蓝牙再打开,一种是在代码中来清除,清除方法也是不能直接调用,采用上述1的方法来实现即可。

public boolean clear(){
    try {

        Method localMethod = bluetoothGatt.getClass().getMethod("refresh");

        if (localMethod != null) {

            return (Boolean) localMethod.invoke(bluetoothGatt);

        }

    } catch (Exception localException) {

      System.out.println("清除异常");

    }

    return false;
}

3、发送类别对应,测试之后发现有些蓝牙需要,有些不需要。

charaWrite.setValue(data);
//无需返回
charaWrite.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);

//需要有返回

 charaWrite.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);

更多蓝牙开发问题可给我留言。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值