Android BLE 藍芽低功耗教程,中央BluetoothGatt和周邊BluetoothGattServer的實現

來源:互聯網
上載者:User

標籤:

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互動了。

 

Demo工程:http://download.csdn.net/detail/jimoduwu/7072515

Android BLE 藍芽低功耗教程,中央BluetoothGatt和周邊BluetoothGattServer的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.