BLE之旅-gatt profile(一)


   从事安卓开发四年余了,但是做蓝牙方向也小有一年多了。以前做开发的时候很少注重积累知识点,但是最近做的不只是蓝牙方向,还有红外和近场nfc通信。感觉很多东西混在一起了真的跟武功秘籍一样,不同场景采用不同的技术实现更为方便。好了不吹牛了,进入正题,主要总结ble开发的知识点。但是只针对gatt frofile通信,其实也是att。主要的几个类:主模式下有BluetoothGatt,BluetoothGattService,BluetoothGattCharacteristic,BluetoothGattCallback几个常用类;从模式下有BluetoothGattServer,BluetoothGattServerCallBack,UUID(特征和服务都有)等。在这里说下之前的ble3.0,之前的通信方式是通过socket的方式进行数据流通信的,而ble4.0和后面的4.1,4.2,以及前不久发布的ble5.0都是通过服务和特征来通信的,根据服务的属性描述和权限限制。

读:通过ble对特征进行读数据;写:对特征写入数据  订阅:就是特征的值变了,app可以自动得到,不用循环去读数据。官网介绍:https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html。

BluetoothGatt
       BluetoothGatt 是开发里最重要最常用到的东西了,我把它理解为 手机与 设备通信的管道。有了这个管道,收发数据就容易了。
         BluetoothGatt 是通过蓝牙设备连接获得:  bluetoothDevice.connectGatt(this.context, false, gattCallback);
                                 先来谈一下这个方法:
                         BluetoothGatt android.bluetooth.BluetoothDevice.connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback)


                          public BluetoothGatt connectGatt (Context context, boolean autoConnect, BluetoothGattCallback callback)
                          Added in API level 18

                          Connect to GATT Server hosted by this device. Caller acts as GATT client. The callback is used to deliver results to Caller,           
                            such as connection status as well as any further GATT client operations. The method returns a BluetoothGatt instance.
                             You   can use BluetoothGatt to conduct GATT client operations.

                               Parameters

                             autoConnect Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true).
                                callback GATT callback handler that will receive asynchronous callbacks.

                                Throws
                           IllegalArgumentException if callback is null
                         --------------------------------------------------------------------------------------
                           autoConnect  为false  立刻发起一次连接
为true  自动连接,只要蓝牙设备变得可用



                           实测发现,用false连接比较好,比较快, true会等个十几秒甚至几分钟才会连接上。  开发过程中一般都是用false,扫描到bluetoothdevice之后,直接用false连接即可。
                           BluetoothGattCallback   是非常重要的回调函数,手机与蓝牙设备的一切通信结果都在这里体现。待会细讲。


BluetoothGattService
            蓝牙设备所拥有的服务。在这里比喻成 班级 吧。bluetoothdevice就比喻成学校吧。 一个学校可以有很多个班级。班级 根据UUID来区别。
BluetoothGattCharacteristic
            蓝牙设备所拥有的特征。比喻成 学生。 一个班级里也可以有很多个学生。学生也是根据UUID 来区别
                当你需要用手机来和蓝牙设备通信的时候,就相当于 你想 和一个学生交流,你得先知道 这个学生的学号,所在班级号,就是开发中的所说的CharacUUID, ServiceUUID。

 安卓主从通信两个demo 主要逻辑见项目截图。BLE之旅-gatt profile(一)_第1张图片qq:602910543。需要


你可能感兴趣的:(Android,ble4.0,主从模式通信,ble4.0通信)