[Android] 藍芽邏輯

SC Tuan
4 min readAug 9, 2017

--

這邊會盡量簡潔扼要地說明Android的藍芽實作邏輯。這邊是參考官方的說明文件,但我會盡量簡單地抽出我個人認為最重要的關鍵詞,你可以透過這些關鍵詞去文件裡面尋找詳細的實作。

取得device的藍芽操控權

要透過BluetoothManager取得BluetoothAdapter。BluetoothAdapter代表該設備的Bluetooth Adapter。

private BluetoothAdapter mBluetoothAdapter;
...
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

確認設備藍芽狀態

透過BluetoothAdapter判斷目前的藍芽是否開啟。

!mBluetoothAdapter.isEnabled()

尋找週遭的藍芽設備

實作上有兩個原則:找到你要的設備就立刻停止。不要無限制的掃描,要設定時間限制。這是為了節省電量。

透過呼叫BluetoothAdapter的startLeScan方法進行掃描:

mBluetoothAdapter.startLeScan(mLeScanCallback)

你也可以限定你想要搜尋的service,帶入代表該service的UUID即可:

startLeScan(UUID[], BluetoothAdapter.LeScanCallback)

參數LeScanCallback是處理搜尋結果的interface,這必須實作,不然你無法看到並處理你的搜尋結果。

與GATT Server連線

當你找到你要的藍芽裝置後,就是要跟裝置內的GATT Server連線了:

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

這會連線到藍芽裝置host的GATT Server。就可以得到藍芽裝置的GATT profile公開的API,亦即,你可以透過mBluetoothGatt來操控藍芽裝置。BluetoothGatt類別就是代表藍芽裝置GATT profile的公開API。

接著,你要實作BluetoothGattCallback(mGattCallback)裡面的方法(onConnectionStateChange),去判斷是否有成功和遠端的GATT server連線。然後便可以查找所連線藍芽裝置內的services。

discoverServices

讀取藍芽裝置資料

接著,你要實作BluetoothGattCallback(mGattCallback)裡面的方法onServicesDiscovered,在這邊去遞迴檢查services及裡面帶有的Characteristics,並對你想要的Characteristics下讀取通知。

BluetoothGATT gatt;
BluetoothGattCharacteristic chara;
//....
gatt.readCharacteristic(chara);
//....
gatt.setCharacteristicNotification(chara,true);

對於下readCharacteristic的Characteristic,實作onCharacteristicRead便可讀取資料。

對於下setCharacteristicNotification的Characteristic,實作BluetoothGattCallback的onCharacteristicRead,就可以接收遠端GATT server更新的資料了。

--

--

SC Tuan

iOS developer(Obj-C & Swift) / Web developer (Java, Javascript, CSS,HTML)