藍(lán)牙ble 4.0 是android在4.3,即API 18引進(jìn)來的鹏漆。APP通過ble可實(shí)現(xiàn)發(fā)現(xiàn)設(shè)備巩梢,查詢服務(wù)和數(shù)據(jù)讀寫的功能。具有更低功耗艺玲。
關(guān)鍵概念:
1.GATT(Generic Attribute Profile): GATT配置文件作為通用規(guī)范括蝠,用于在ble鏈路上發(fā)送和接收數(shù)據(jù)塊。配置文件是設(shè)備如何在特定的應(yīng)用程序中工作的規(guī)格說明饭聚。一個(gè)設(shè)備可以實(shí)現(xiàn)多個(gè)配置文件忌警。
2.ATT(Attribute Protocol):每個(gè)屬性通過一個(gè)唯一的統(tǒng)一標(biāo)識(shí)符(UUID)來實(shí)現(xiàn),每個(gè)String類型的UUID使用128 bitb標(biāo)準(zhǔn)格式秒梳。
3. Characteristic: 一個(gè)Characteristic包括一個(gè)單一的變量和N個(gè)用來描述Characteristic變量的descriptor法绵。
4.Descriptor :用來描述Characteristic變量的屬性。
5.Service:是Characteristic的集合酪碘。
具體實(shí)現(xiàn):
1.實(shí)現(xiàn)BluetoothGattCallback回調(diào):
private final BluetoothGattCallback mGattCallback=new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if(status == BluetoothGatt.GATT_SUCCESS) {
bleSetState(State.from(newState));
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if(status == BluetoothGatt.GATT_SUCCESS) {
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
if(mCallback!=null) {
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, intstatus) {
if(mCallback!=null) {
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, intstatus) {
if(mCallback!=null) {
}
}
@Override
public void onDescriptorRead(BluetoothGatt gatt,BluetoothGattDescriptor descriptor, intstatus) {
if(mCallback!=null) {
}
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt,BluetoothGattDescriptor descriptor, intstatus) {
if(mCallback!=null) {
}
}
};
2. 得到BluetoothAdapter:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
3.得到BluetoothDevice:
BluetoothDevice device = adapter.getRemoteDevice(mac);
4.執(zhí)行具體的連接朋譬,斷開等操作
BluetoothGatt mBluetoothGatt = device.connectGatt(context, false, mCallback);
//disconnect
mBluetoothGatt.disconnect();
//close
mBluetoothGatt.close();
//獲取BluetoothGattCharacteristic
BluetoothGattService gattService =mBluetoothGatt.getService(UUID_IR_SERVICE);
BluetoothGattCharacteristic characteristic = gattService.getCharacteristic(UUID_IR_CTRL);
5.數(shù)據(jù)之間的傳輸(重點(diǎn))
int writeType = BluetoothGattCharacteristic.PROPERTY_WRITE;
characteristic.setWriteType(writeType);
characteristic.setValue(values); //value就是封裝好的byte[]
mBluetoothGatt.writeCharacteristic(characteristic)
目前為止,一個(gè)最基本的藍(lán)牙ble開發(fā)就差不多了兴垦。
回頭再整理整理此熬,希望能做個(gè)demo上傳到github上。