Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 藍牙 4.0(BLE)開發入門與關鍵回調解析

編輯:關於 Android 開發

Android 藍牙 4.0(BLE)開發入門與關鍵回調解析

最近一直在研究一個藍牙功能,由於本人是菜鳥,學起來比較費勁,折騰了好久才弄懂。網上關於藍牙 4.0 的內容多半是幾個 Demo 抄來抄去,而且全是英文註解,對英文不好的朋友來說實在吃力,一些沒必要的描述囉裡吧嗦,關鍵的方法介面卻一筆帶過。於是這裡就來介紹一些網上常被略過、但其實相當重要的介面回調。

藍牙中常見的幾個要素:藍牙名稱(name)、藍牙位址(address)、訊號強度(rssi)、藍牙服務(service),而服務下面又有具體的小服務,也就是實際要操作的部分。

藍牙通訊過程:開啟 → 查找(可指定 UUID 查找裝置)→ 連接。連接之後,首先取得 Bluetooth Service(透過 UUID 查找),再找到 service 裡面的 Bluetooth Characteristic(同樣以 UUID 取得),之後就能對它進行讀寫。

以下重點介紹網上多半一筆帶過的 BluetoothGattCallback 回調:

BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {

    // 連接狀態觸發
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            Log.d("Bluetooth", "-------ConnectSucceed------");
            bluetoothGatt.discoverServices(); // 發現服務
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            Log.d("Bluetooth", "-------Disconnect------");
            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
                bluetoothAdapter = bluetoothManager.getAdapter();
                bluetoothAdapter.enable();
                bluetoothAdapter.startLeScan(uuid, leScanCallback);
            }
        }
    }

    // 發現裝置服務回調
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            String open = "open=1"; // 發送的數據
            try {
                byte[] data = open.getBytes("UTF-8");
                writeDataToDevice(data); // 發送
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.d("000", "--------發送數據成功----- status:");
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        Log.d("藍牙回復數據為", characteristic.getValue().toString());
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    }
};

向裝置發送資料的方法:

/**
 * 向設備發送數據
 */
public void writeDataToDevice(byte[] data) {
    if (bluetoothGatt == null) {
        Log.d("00", "----BluetoothGatt=null----");
        return;
    }
    bluetoothGattService = bluetoothGatt.getService(BLURTOOTH_SERVICE); // 服務的UUID
    if (bluetoothGattService == null) {
        bluetoothGatt.disconnect();
        return;
    }
    BluetoothGattCharacteristic mCharac = bluetoothGattService.getCharacteristic(BLUETOOTH_CHARACTERISTIC); // 特性的UUID
    if (mCharac == null) {
        bluetoothGatt.disconnect();
        return;
    }
    bluetoothGatt.setCharacteristicNotification(mCharac, true);
    mCharac.setValue(data); // 設置需要發送的數據
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    writeCharacteristic(mCharac);
}

看完後搭配一個 Demo 會更清晰。做開發還是建議多讀原始碼、理解原理,別只是複製張貼;真正看懂了,運用起來才會靈活。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved