安卓蓝牙技术之中央BluetoothGatt和周边BluetoothGattServer的实现

BluetoothAdapter.LeScanCallback 

Class Overview:
回调接口被用于传输LE扫描后的结果;

详情请查:

startLeScan(LeScanCallback)

startLeScan(UUID[], LeScanCallback)

onLescan(BluetoothDevice , int , byte[])

是通过startLeScan(BlueToothAdapter.LeScanCallback)函数调用之后 , 会初始化一个device对象 ; 当一个LE设备被发现的时候 , 这个对象device作为参数传递进来 ,

device : 识别的远程设备

rssi : RSSI的值作为对远程蓝牙设备的报告; 0代表没有蓝牙设备;

scanRecode: 远程设备提供的配对号(公告)



.创建一个周边(虽然目前周边APIAndroid手机上不工作,但还是看看)

 a)先看看周边用到的class,蓝色椭圆

安卓蓝牙技术之中央BluetoothGatt和周边BluetoothGattServer的实现


b)说明:

每一个周边BluetoothGattServer,包含多个服务Service,每一个Service包含多个特征Characteristic

1.new一个特征:character = new BluetoothGattCharacteristic(

UUID.fromString(characteristicUUID),

BluetoothGattCharacteristic.PROPERTY_NOTIFY,

BluetoothGattCharacteristic.PERMISSION_READ);

2.new一个服务:service = new BluetoothGattService(UUID.fromString(serviceUUID),

BluetoothGattService.SERVICE_TYPE_PRIMARY);

3.把特征添加到服务:service.addCharacteristic(character);

4.获取BluetoothManager

manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

5.获取/打开周边:BluetoothGattServer server = manager.openGattServer(this,

new BluetoothGattServerCallback(){...}); 

6.service添加到周边:server.addService(service);

7.开始广播serviceGoogle还没有广播ServiceAPI,等吧!!!!!所以目前我们还不能让一个Android手机作为周边来提供数据。

 


.创建一个中央(这次不会让你失望,可以成功创建并且连接到周边的)

a)先看看中央用到的class,蓝色椭圆

安卓蓝牙技术之中央BluetoothGatt和周边BluetoothGattServer的实现

b)说明:

为了拿到中央BluetoothGatt,可要爬山涉水十八弯:

1.先拿到BluetoothManager

bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

2.再拿到BluetoothAdaptbtAdapter = bluetoothManager.getAdapter();

3.开始扫描:btAdapter.startLeScan( BluetoothAdapter.LeScanCallback);

4.LeScanCallback中得到BluetoothDevicepublic void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {.....}

5.BluetoothDevice得到BluetoothGattgatt = device.connectGatt(this, true, gattCallback);

终于拿到中央BluetoothGatt了,它有一堆方法(查API吧),调用这些方法,你就可以通过BluetoothGattCallback和周边BluetoothGattServer交互了。