蓝牙Ble开发
BLE: Bluetooth Low Energy,即蓝牙低功耗,它是一种技术,从蓝牙4.0开始支持。蓝牙低功耗芯片有两种模式:单模和双模。
单模:只能执行低功耗协议栈,也就是只支持ble。
双模:支持传统蓝牙以及ble的使用。
较传统蓝牙:传输速度更快,覆盖范围更广,安全性更高,延迟更短,耗电低等优点。
UUID(UniversallyUnique Identifier),含义是通用唯一识别码,它是在一定范围内唯一的机器生成的标识符。标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12)。
二、Android
注意:Android 4.3(API18)引入ble相关接口。
相关类:目录:frameworks/base/core/java/android/bluetooth/
BluetoothGatt:中央使用和处理数据;
BluetoothGattCallback:中央的回调。
BluetoothGattServer:周边提供数据;
BluetoothGattServerCallback:周边的回调
BluetoothGattService:Gatt服务
BluetoothGattCharacteristic:Gatt特性
BluetoothGattDescriptor:Gatt描述
1. 权限
<uses-permissionandroid:name="android.permission.BLUETOOTH"/>
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"/>"
6.0以上的系统还需要加定位权限:<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 如果想声明你的app只为具有BLE的设备提供,在manifest文件中包括:
<uses-featureandroid:name="android.hardware.bluetooth_le"android:required="true"/>
2. 检查设备是否支持ble,下面返ture说明支持
getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
3. 搜索设备
搜索附近所有的外围设备:mBluetoothAdapter.startLeScan(mLeScanCallback);
搜索某些uuid的外围设备:mBluetoothAdapter.startLeScan(uuid[],mLeScanCallback);
停止扫描:mBluetoothAdapter.stopLeScan(mLeScanCallback);
4. 扫描结果监听:device是扫描的设备;rssi 信号强度;scanRecord 远程设备广告记录的内容(蓝牙名称)
private BluetoothAdapter.LeScanCallback mLeScanCallback=new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { } };
描指定类型的外围设备:mBluetoothAdapter.startLeScan(UUID[], BluetoothAdapter.LeScanCallback));
5. 连接设备
a)
连接:mBluetoothGatt =device.connectGatt(this, false, mGattCallback);
注:
方法需要三个参数:一个Context对象,自动连接(boolean值,表示只要BLE设备可用是否自动连接到它),和BluetoothGattCallback调用。
连接到GATT服务端时,由BLE设备做主机,并返回一个BluetoothGatt实例,然后你可以使用这个实例来进行GATT客户端操作。请求方(Android app)是GATT客户端。BluetoothGattCallback用于传递结果给用户,例如连接状态,以及任何进一步GATT客户端操作