1. 程式人生 > >Android BluetoothGatt和周邊BluetoothGattServer的實現

Android BluetoothGatt和周邊BluetoothGattServer的實現

轉至:http://blog.csdn.net/wave_1102/article/details/39271693

Android4.3 規範了BLE的API,但是直到目前的4.4,還有些功能不完善。

在BLE協議中,有兩個角色,周邊(Periphery)和中央(Central);周邊是資料提供者,中央是資料使用/處理者;在iOS SDK裡面,可以把一個iOS裝置作為一個周邊,也可以作為一箇中央;但是在Android SDK裡面,直到目前最新的Android4.4.2,Android手機只能作為中央來使用和處理資料;那資料從哪兒來?從BLE裝置來,現在的很多可穿戴裝置都是用BLE來提供資料的。

一箇中央可以同時連線多個周邊,但是一個周邊某一時刻只能連線一箇中央。

大概瞭解了概念後,看看Android BLE SDK的四個關鍵類(class):

a)BluetoothGattServer作為周邊來提供資料;BluetoothGattServerCallback返回周邊的狀態。

b) BluetoothGatt作為中央來使用和處理資料;BluetoothGattCallback返回中央的狀態和周邊提供的資料。

因為我們討論的是Android的BLE SDK,下面所有的BluetoothGattServer代表周邊,BluetoothGatt代表中央。

一.建立一個周邊(雖然目前周邊API在Android手機上不工作,但還是看看)

 a)先看看周邊用到的class,藍色橢圓


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.開始廣播service:Google還沒有廣播Service的API,等吧!!!!!所以目前我們還不能讓一個Android手機作為周邊來提供資料。

二.建立一箇中央(這次不會讓你失望,可以成功建立並且連線到周邊的)

a)先看看中央用到的class,藍色橢圓


b)說明:

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

1.先拿到BluetoothManager:bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

2.再拿到BluetoothAdapt:btAdapter = bluetoothManager.getAdapter();

3.開始掃描:btAdapter.startLeScan( BluetoothAdapter.LeScanCallback);

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

5.用BluetoothDevice得到BluetoothGatt:gatt = device.connectGatt(this, true, gattCallback);

終於拿到中央BluetoothGatt了,它有一堆方法(查API吧),呼叫這些方法,你就可以通過BluetoothGattCallback和周邊BluetoothGattServer互動了。

From: http://blog.csdn.net/jimoduwu/article/details/21604215