分享Android 蓝牙4.0(ble)开发的解决方案

2019-12-10 18:47:32于海丽
这篇文章主要为大家分享了Android 蓝牙4.0(ble)开发的解决方案,感兴趣的小伙伴们可以参考一下  

最近,随着智能穿戴式设备、智能医疗以及智能家居的普及,蓝牙开发在移动开中显得非常的重要。由于公司需要,研究了一下,蓝牙4.0在Android中的应用。

以下是我的一些总结。

1.先介绍一下关于蓝牙4.0中的一些名词吧:   
(1)、GATT(Gneric Attibute  Profile)

通过ble连接,读写属性类小数据Profile通用的规范。现在所有的ble应用Profile  都是基于GATT
(2)、ATT(Attribute Protocal)
GATT是基于ATT Potocal的ATT针对BLE设备专门做的具体就是传输过程中使用尽量少的数据,每个属性都有个唯一的UUID,属性chartcteristics and Service的形式传输。

(3)、Service是Characteristic的集合。
(4)、Characteristic 特征类型。

比如,有个蓝牙ble的血压计。他可能包括多个Servvice,每个Service有包括多个Characteristic

注意:蓝牙ble只能支持Android 4.3以上的系统 SDK>=18

2.以下是开发的步骤:
2.1首先获取BluetoothManager 

 

复制代码 BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 

 

2.2获取BluetoothAdapter

 

复制代码 BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter(); 

 

2.3创建BluetoothAdapter.LeScanCallback

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { 
 
  @Override 
  public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) { 
 
   runOnUiThread(new Runnable() { 
    @Override 
    public void run() { 
     try { 
      String struuid = NumberUtils.bytes2HexString(NumberUtils.reverseBytes(scanRecord)).replace("-", "").toLowerCase(); 
      if (device!=null && struuid.contains(DEVICE_UUID_PREFIX.toLowerCase())) { 
       mBluetoothDevices.add(device); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
   }); 
  } 
 };