一、创建中央基本概念
1.1、中央涉及的类有:
说明:为了拿到中央BluetoothGatt,需要经历以下过程:
1、先拿到BluetoothManager:bluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
2、再拿到BluetoothAdapter:bluetoothAdapter=bluetoothManager.getAdapter();
3、开始扫描:bluetoothAdapter.startLeScan(BluetoothAdpater.LeScanCallback);
4、从LeScanCallback中得到BluetoothDevice:public void onLeScan(BluetoothDevice device,int rssi,byte[] scanRecord){……};
5、用BluetoothDevice得到BluetoothGatt:gatt=device.connectGatt(this,true,gattCallback);
6、接下来调用BluetoothGatt的方法,通过BluetoothGattCallback和周边的BluetoothServer进行交互
1.2、扫描以及读取与写入数据的相关概念:
监听扫描结果:
mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {}
};
device 搜索到的bye设备。
rssi 信号强度
scanRecord 远程设备广告记录的内容(蓝牙名称)
发起连接请求,获得中央。
mBluetoothGatt = device.connectGatt(mContext, false,mGattCallback);
第二个参数autoConnect 如果为false直接立即连接。
true 等待远程设备可用时(在范围内,。。)连接。并不是断开后重新连接。
第三个参数 Gatt callback 。
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {};
连接成功后,发送 gatt服务发现请求。
//连接状态改变回调
onConnectionStateChange(BluetoothGatt gatt, int status, int newState){
if(newState == BluetoothProfile.STATE_CONNECTED){
//连接成功后,发送发现服务请求。
mBluetoothGatt.discoverServices();
}
}
//发现服务回调。
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if(status == BluetoothGatt.GATT_SUCCESS){
//发现成功后,则可以通过下面方法获取service 列表。
mBluetoothGatt.getServices();
}
}
1.3、中央与周边的数据交互过程总结(写入):
1、当点击事件调用该方法时BluetoothGatt.writeCharacteristic(characteristic),
a、系统异步回调onCharacteristicChanged()方法,
b、与此同时服务端:系统回调onCharacteristicWriteRequest()方法,通过该方法的参数value得到客户端发送过来的数据,在该回调方法中调用sendResponse()回复客户端响应成功,接着处理接受的数据,并通过BluetoothGattServer.notityCharacteristicChanged(device,characteristicRead,false)将回应的数据发送给客户端,该回应的数据就通过onCharacteristicChanged()方法的参数传递到客户