Anroid连接BLE的两个坑

因为项目有个需要连接ble设备的,有些手机能够连接上,有些手机就会一直报status=133的错误。

原因有两个:

1、断开连接用的BluetootGatt.disconnect(),这样只是断开连接,并没有关闭,因为BluetoothGatt连接个数有限制,所以必须关闭连接:

     **
     * Close this Bluetooth GATT client.
     *
     * Application should call this method as early as possible after it is done with
     * this GATT client.
     */

所以,每次使用完连接后必须调用BluetoothGatt.close();

2、 如果以上已经做好,却发现还是出现status=133,此时错误很可能是传输层的模式的问题。在android5.0(不包括)以下,不支持设置模式,连接ble的函数为:

public BluetoothGatt connectGatt(Context context, boolean autoConnect,BluetoothGattCallback callback)

而5.0和5.1两个版本内部源码多了一个新的连接方法,但是此方法不公开,可以通过反射调用:

/**
     * @param transport preferred transport for GATT connections to remote dual-mode devices
     *             {@link BluetoothDevice#TRANSPORT_AUTO} or
     *             {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE}
     */
    public BluetoothGatt connectGatt(Context context, boolean autoConnect,
                                     BluetoothGattCallback callback, int transport)


其中的transport就是设置传输层模式的,根据源码,一共有三种模式,默认是TRANSPORT_AUTO。

6.0及以上版本这个方法是公开的,不需要用反射来调用了。

/**
      * No preferrence of physical transport for GATT connections to remote dual-mode devices
      */
    public static final int TRANSPORT_AUTO = 0;

    /**
     * Prefer BR/EDR transport for GATT connections to remote dual-mode devices
     */
    public static final int TRANSPORT_BREDR = 1;

    /**
     * Prefer LE transport for GATT connections to remote dual-mode devices
     */
    public static final int TRANSPORT_LE = 2;

有些5.0及5.1的手机可以通过反射将transport设置为TRANSPORT_LE,然后就可以连接。而实际情况下,有些ble设备还是无法连接,这时可以再换用TRANSPORT_BREDR来试试。而TRANSPORT_LE和TRANSPORT_BREDR具体代表的意思就需要去咨询专门做蓝牙的技术人员了。


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值