您的位置:首页 > 移动开发 > Android开发

Android蓝牙BLE(二)--使用蓝牙主机

2016-06-11 22:58 495 查看
使用BLE作为主机(中心设备)时,需要在附近有可扫描的从机设备,通过扫描设备、连接设备后,则可进行传输操作。其中每次能传输的数据大小,多由从机设备决定,目前外围低功耗BLE设备每次只能传输20Byte,当用Ios和android作服务端时,可单次传输更多的数据。

一、获取蓝牙管理类

BluetoothManager :用来管理Adapter、获取连接状态之类,别个创建外围设备时需要用它来创建GattServer。

BluetoothAdapter :BLE的一系列打开、关闭、扫描,以及一些硬件信息均能在该类中获取。

相应的获取如下:


final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();


二、扫描广播

使用BluetoothAdapter可以扫描周围的外围设备,扫描设备是一个非常耗电的操作,需要及时关闭扫描,扫描的信息会通过回调LeScanCallback返回,其中最常用的Mac地址被作为唯一标识符,可用来连接外围设置,另外扫描回调是多线程的,最好使用Handler返回扫描结果。

扫描代码:

mBluetoothAdapter.startLeScan(mLeScanCallback);

private LeScanCallback mLeScanCallback = new LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
if (device == null) {
return;
}
EndpointDeviceInfo scan = new EndpointDeviceInfo();
scan.setUniqueAddress(device.getAddress());
scan.setName(device.getName());
mConnectionHandler.obtainMessage(
BT_BLE_CONNECTION_MESSAGE_FOUND_DEVICE, -1, -1, scan)
.sendToTarget();
cancelSearch();
}
};


三、连接设备

扫描到了设备后,通过MAC地址就可以远程设备,通过连接操作,即可得到BluetoothGatt服务,有这BluetoothGatt则通过UUID,可获取相关的BluetoothDevice,再而获取特征符和描述符。

连接操作如下:

public void connect(String address) {
mDevice = mBluetoothAdapter.getRemoteDevice(address);
if (mDevice == null) {
Log.e(TAG, "device is null");
mConnectionHandler.obtainMessage(
BT_BLE_CONNECTION_MESSAGE_CANNOT_CONNECT).sendToTarget();
return;
}
mGatt = mDevice.connectGatt(mContext, false, mBluetoothGattCallback);
}


四、连接服务

在第三个步骤中,获取到了BluetoothGatt,通过对应的UUID则可获取相关的具体操作类。如下:

BluetoothGattService service = mGatt.getService(UUID
.fromString(SERVICE_UUID));
mCharacteristic = service.getCharacteristic(UUID
.fromString(CHARACTERISTIC_UUID));


五、发送数据

当需要向外围设备端发送数据时,可在BluetoothGattCharacteristic中设备值,再通过BluetoothGatt即可发起数据传输。

byte[] header = new byte[6];
mCharacteristic.setValue(header);
boolean bool = mGatt.writeCharacteristic(mCharacteristic);


六、监听特征符

当通过BluetoothGattService获取到的特征符,并不代表特征符已经关联,而还需要设置监听,

mGatt.setCharacteristicNotification(mCharacteristic, true)


通过上面语句则可使能notifications/indications两种BLE模式。同时,还必需实现BluetoothGattCallback接口,当有新数据时,将通过下面接口回调数据。

public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status)


七、BLE状态监听

当设置BluetoothGattCallback回调后,BLE发现新服务、连接状态发生改变时都可以实现监听,当外围设备有读和写请求也会通过onCharacteristicRead和onCharacteristicWrite回调。

接收数据:

public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
// 第一次获取的是head信息
if (!mIsReceivingData) {
handleHeader(characteristic.getValue());
} else {
handleData(characteristic.getValue());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BLE 蓝牙 android