版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/Achilles_Lee/article/details/78321589
引入
蓝牙4.0为低功耗蓝牙,从安卓4.4版本开始支持。安卓中蓝牙的基本使用在官方的指南中有详细的说明,地址如下:https://developer.android.google.cn/guide/topics/connectivity/bluetooth-le.html
- 结合项目中的开发需求,经常需要在一个app中连接多种设备,如果设备的传输协议一致的话,那么设备与app之间传输指令可以公用一套代码。可是现实情况复杂,经常项目开发到一半就需要兼容新的设备。如果在项目的一开始,就可以做一个高扩展的兼容多设备的sdk,那么不管是以后其他项目使用,还是再添加新设备兼容,都将是一个不错的选择。
android提供的api简介
- 获取蓝牙的管理adapter(在获取之前,记得检查权限)
private BluetoothAdapter mBluetoothAdapter;
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
- 检查蓝牙是否可用,返回true,表明支持4.0低功耗蓝牙。
mBluetoothAdapter.isEnabled()
- 扫描蓝牙设备
- BluetoothAdapter.LeScanCallback为扫描的回调函数。扫描到了设备,会在onLeScan中回调(不过要留意的是,同一个设备可能会被多次返回,在显示时,记得通过mac码进行筛选)。
- 开启和停止扫描的方法也很方便。
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
//device 为扫描到的设备
}
};
mBluetoothAdapter.startLeScan(mLeScanCallback);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
下来就是连接设备了, 其中 import android.bluetooth.BluetoothGattCallback;是一个抽象类。与蓝牙设备的连接回调都在这个类中。分别是:
onConnectionStateChange 连接状态改变。当判断这个方法的入参数符合以下两个条件时,则表示已经连接成功(蓝牙设备给手机传输数据时是通过设备的通道传输数据的,但是连接上之后,设备的通道此时并没有打开,此时可进行通道打开操作)。
status == GATT_SUCCESS && newState == BluetoothGatt.STATE_CONNECTED
onServicesDiscovered 发现服务
- onCharacteristicRead 读取字符
- onCharacteristicWrite 写入指令成功
- onCharacteristicChanged 蓝牙回传数据处理
- onDescriptorRead 读的描述返回
- onDescriptorWrite 写的描述返回
- onReliableWriteCompleted
- onReadRemoteRssi 手机距离设备的远近
BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(address);
BluetoothGatt bluetoothGatt = remoteDevice.connectGatt(appContext, isAutoConnect, mBluetoothGattCallback);
- 发送数据给蓝牙设备(其中服务通道,数据通道,指令,是根据蓝牙设备协议确定的)
String serveGallery = "xxx-xxx-xxx-xxx";//服务通道
String gallery = "xxx-xxx-xxx-xxx";//数据通道
BluetoothGattCharacteristic bluetoothGattCharacteristic = bleGattCharMap.get(serveGallery).get(gallery);
bluetoothGattCharacteristic.setValue(new byte[]{ (byte) 0XBE, 0X02,0X03, (byte) 0XED}); //byte 为指令
bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
- 发送数据成功后,返回的数据会在上面实例的BluetoothGattCallback类的回调方法中回应,再根据业务需求做相应的处理。
以上是android api中提供的蓝牙的基本使用流程。至于怎么兼容多设备的问题,请看下一篇。