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

Android iBeacon 開發入門:BLE 掃描與資料解析實作

編輯:關於 Android 程式設計

iBeacon 的工作原理建立在 Bluetooth Low Energy(BLE,低功耗藍牙)之上。iBeacon 基站會持續向四周廣播音訊號,當行動裝置進入其覆蓋範圍時就能接收到。由於這是一項開放技術標準,任何符合規範的裝置都能使用,Android 自然也不例外——Google 從 Android 4.3 開始支援 BLE。

定位一直是極關鍵的能力。透過部署 iBeacon 基站可以實現室內導航,同時也能推送訊息,在百貨零售、體育館、博物館等場景中能帶來很不錯的體驗。加上藍牙本身傳輸距離足、功耗低、支援訊號加密,iBeacon 在行動支付領域也頗具想像空間。

先理解 BLE

BLE(又稱 Bluetooth Smart)最早可追溯到 Nokia 在 2006 年提出的 Wibree,後來併入藍牙標準,成為 Bluetooth 4.0 的一部分。目前市面上常見三類藍牙裝置:

  • Bluetooth:僅支援傳統模式的裝置
  • Bluetooth Smart Ready:同時支援傳統與低功耗雙模式的裝置
  • Bluetooth Smart:僅支援低功耗藍牙的裝置

BLE 相比傳統藍牙最大的優勢是功耗降低約九成,同時傳輸距離更長(可超過 100 公尺),並在安全性與穩定性上有所提升(支援 AES 加密與 CRC 驗證)。

iBeacon 本身還有幾個特點:

  • 無需配對。一般藍牙裝置在印象中都需要配對才能工作,但 iBeacon 走的是藍牙的廣播通道,因此完全免配對。
  • 可後台喚醒。iBeacon 的訊息推送需要 App 支援,但接收訊號本身不需要開啟 App,只要確認已安裝且手機藍牙已開啟即可。

iBeacon 的資料結構

基站透過廣播通道持續對外發送位置資訊,發送頻率越高越耗電。要注意的是,iBeacon 本身並不推送訊息,它只用於定位;推播功能必須由 App 自行實作。Apple 定義了其中 32 位元的廣播資料格式:

  • UUID:廠商標識碼
  • Major:群組號,同一組內的 Beacon 共用相同的 Major
  • Minor:群組內個別 Beacon 的識別碼
  • TX Power:用於估算裝置與 Beacon 之間的距離

UUID + Major + Minor 三者共同構成一個 Beacon 的唯一識別,概念上有點類似網路上的 IP 位址加埠號。TX Power 則是測距依據,iBeacon 目前只定義了三個粗略等級:

  • 非常近(Immediate):約 10 公分內
  • 近(Near):1 公尺內
  • 遠(Far):1 公尺外

實作:取得 BluetoothAdapter 並開始掃描

final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothAdapter.startLeScan(mLeScanCallback);

掃描回呼:依距離排序

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        final iBeaconClass.iBeacon ibeacon =
                iBeaconClass.fromScanData(device, rssi, scanRecord);
        addDevice(ibeacon);
        // rssi 越大代表訊號越強、距離越近
        Collections.sort(mLeDevices, new Comparator<iBeaconClass.iBeacon>() {
            @Override
            public int compare(iBeaconClass.iBeacon h1, iBeaconClass.iBeacon h2) {
                return h2.rssi - h1.rssi;
            }
        });
    }
};

把掃描結果加入集合

private ArrayList<iBeaconClass.iBeacon> mLeDevices = new ArrayList<iBeaconClass.iBeacon>();

private void addDevice(iBeaconClass.iBeacon device) {
    if (device == null) {
        Log.d("DeviceScanActivity", "device == null");
        return;
    }
    // 依藍牙位址判斷是否已在清單中,有則更新、無則新增
    for (int i = 0; i < mLeDevices.size(); i++) {
        if (mLeDevices.get(i).bluetoothAddress.equals(device.bluetoothAddress)) {
            mLeDevices.set(i, device);
            return;
        }
    }
    mLeDevices.add(device);
}

這裡的去重邏輯很重要。onLeScan() 的呼叫頻率相當高,同一個 Beacon 會被反覆回報,若不檢查藍牙位址就無條件加入,清單很快就會塞滿重複項目。

解析廣播封包

在 iBeaconClass 中進行資料解析,實作思路參考 AltBeacon/android-beacon-library:

public class iBeaconClass {

    static public class iBeacon {
        public String name;
        public int major;
        public int minor;
        public String proximityUuid;
        public String bluetoothAddress;
        public int txPower;
        public int rssi;
    }

    public static iBeacon fromScanData(BluetoothDevice device, int rssi, byte[] scanData) {
        int startByte = 2;
        boolean patternFound = false;

        // 尋找 iBeacon 的廣播前綴標記
        while (startByte <= 5) {
            if (((int) scanData[startByte + 2] & 0xff) == 0x02
                    && ((int) scanData[startByte + 3] & 0xff) == 0x15) {
                // Apple 的 iBeacon 固定前綴
                patternFound = true;
                break;
            } else if (((int) scanData[startByte] & 0xff) == 0x2d
                    && ((int) scanData[startByte + 1] & 0xff) == 0x24
                    && ((int) scanData[startByte + 2] & 0xff) == 0xbf
                    && ((int) scanData[startByte + 3] & 0xff) == 0x16) {
                // Estimote 的封包格式
                iBeacon ibeacon = new iBeacon();
                ibeacon.major = 0;
                ibeacon.minor = 0;
                ibeacon.proximityUuid = "00000000-0000-0000-0000-000000000000";
                ibeacon.txPower = -55;
                return ibeacon;
            } else if (((int) scanData[startByte] & 0xff) == 0xad
                    && ((int) scanData[startByte + 1] & 0xff) == 0x77
                    && ((int) scanData[startByte + 2] & 0xff) == 0x00
                    && ((int) scanData[startByte + 3] & 0xff) == 0xc6) {
                iBeacon ibeacon = new iBeacon();
                ibeacon.major = 0;
                ibeacon.minor = 0;
                ibeacon.proximityUuid = "00000000-0000-0000-0000-000000000000";
                ibeacon.txPower = -55;
                return ibeacon;
            }
            startByte++;
        }

        if (!patternFound) {
            // 不是 iBeacon 封包
            return null;
        }

        iBeacon ibeacon = new iBeacon();
        ibeacon.major = (scanData[startByte + 20] & 0xff) * 0x100
                + (scanData[startByte + 21] & 0xff);
        ibeacon.minor = (scanData[startByte + 22] & 0xff) * 0x100
                + (scanData[startByte + 23] & 0xff);
        ibeacon.txPower = (int) scanData[startByte + 24];  // 此位元組為有號數
        ibeacon.rssi = rssi;

        // AirLocate 封包範例:
        // 02 01 1a 1a ff 4c 00 02 15   Apple 固定前綴
        // e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0   iBeacon profile uuid
        // 00 00   major
        // 00 00   minor
        // c5      校準後的 Tx Power(2 的補數)

        byte[] proximityUuidBytes = new byte[16];
        System.arraycopy(scanData, startByte + 4, proximityUuidBytes, 0, 16);
        String hexString = bytesToHexString(proximityUuidBytes);

        StringBuilder sb = new StringBuilder();
        sb.append(hexString.substring(0, 8)).append("-");
        sb.append(hexString.substring(8, 12)).append("-");
        sb.append(hexString.substring(12, 16)).append("-");
        sb.append(hexString.substring(16, 20)).append("-");
        sb.append(hexString.substring(20, 32));
        ibeacon.proximityUuid = sb.toString();

        if (device != null) {
            ibeacon.bluetoothAddress = device.getAddress();
            ibeacon.name = device.getName();
        }
        return ibeacon;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}

幾個實務要點

位元運算的意義。程式碼中到處可見 & 0xff,這是因為 Java 的 byte 是有號數(範圍 -128 到 127),直接轉成 int 時負數會被擴展成很大的值。做 AND 運算可以強制取後 8 位元,得到正確的 0 到 255。

大端序組裝。Major 與 Minor 都是 16 位元的無號整數,需要把連續兩個位元組組合成 高8位 * 256 + 低8位,這就是大端序(Big-Endian)的還原方式。

權限與版本限制。Android 6.0 之後掃描藍牙需要位置權限;Android 12 以上則改為 BLUETOOTH_SCAN 權限,並需宣告 neverForLocation 或同時具備位置權限。startLeScan() 在 API 31 已標記為 deprecated,新專案建議改用 BluetoothLeScanner 搭配 ScanFilter 與 ScanSettings。

掃描必須停止。持續掃描非常耗電,實務上應在找到目標裝置或離開頁面時立刻呼叫 stopLeScan(),並在 onPause() 中確保釋放。

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