1.蓝牙搜索.
首先是获取BluetoothAdapter对象:
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
当bluetoothAdapter不为空时代表设备支持BLE4.0.
然后调用BluetoothAdapter 的startLeScan(callback)方法,这里需要传入一个callBack对象,用于搜到设备时回调。
实现如下:
private BluetoothAdapter.LeScanCallback callback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//如果搜到设备,将会执行这里,device即是搜到的设备。一般这里需要将搜到的设备添加到listView的适配器中,用于显示到界面
}
});
}
};
停止搜索调用BluetoothAdapter的stopLeScan(callback)方法。
2.链接蓝牙以及接收数据.
连接蓝牙代码如下:
BluetoothGatt bluetoothGatt = device.connectGatt(this, false, mGattCallback);
第一个参数是Context对象,第二个参数表示是否自动连接,第三个是一个CallBack对象,当设备连接状态发生改变,数据的收发状态改变时回调。
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {//连接成功
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//断开连接
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
byte[] data = characteristic.getValue();//如果连接设备发送数据到手机端,将通过这个函数获取数据。
}
};
device是第一步搜到的设备BluetoothDevice对象,也可以通过获取该设备的MAC地址,然后再获取BluetoothDevice对象:
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceMAC);
如果bluetoothGatt不为空,则连接成功.
3.蓝牙发数据.
通过BLE发送数据时,需要知道连接设备的一些服务UUID,一般UUID都类似。
public static final UUID SERVICE = UUID
.fromString("0000FFF0-0000-1000-8000-00805F9B34FB");
public static final UUID SEND_UUID = UUID
.fromString("0000FFF6-0000-1000-8000-00805F9B34FB");
public static final UUID RECEIVE_UUID = UUID
.fromString("0000FFF7-0000-1000-8000-00805F9B34FB");
public static final UUID CCC = UUID
.fromString("00002902-0000-1000-8000-00805f9b34fb");
有了这些UUID后就可以开始发送数据:
BluetoothGattService bluetoothGattService = bluetoothGatt
.getService(SERVICE); //获取UUID对应的服务。
BluetoothGattCharacteristic charac = bluetoothGattService
.getCharacteristic(SEND_UUID); //获取指定服务下的特性
然后就是注册一个数据接收通知
if (bluetoothGatt.setCharacteristicNotification(charac, true)) {
BluetoothGattDescriptor clientConfig = charac
.getDescriptor(CCC);
if (clientConfig != null) {
clientConfig
.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
bluetoothGatt.writeDescriptor(clientConfig);
}
}
charac.setValue(data); //这里将要发送的数据加入该特性中,data 类型为byte数组,如果数据超过20字节需要在每次发送加入间隔。
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
bluetoothGatt.writeCharacteristic(charac);//发送数据