萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android iBeacon 掃描實戰:解析 scanRecord 識別 Apple iBeacon 廣播幀

iBeacon 廣播幀結構

iBeacon 為 Apple 定義的 BLE 廣播格式,廣播數據包含在 BluetoothAdapter.LeScanCallback.onLeScan(device, rssi, scanRecord) 的 scanRecord 字節數組中。標準前綴 (AD 結構):

Offset | Length | Value          | Meaning
-------|--------|----------------|------------------------
0      | 1      | 0x02           | Flags AD Length
1      | 1      | 0x01           | Flags AD Type
2      | 1      | 0x1A           | Flags Data (LE General Discoverable + BR/EDR Not Supported)
3      | 1      | 0x1A           | iBeacon AD Length (26 bytes)
4      | 1      | 0xFF           | Manufacturer Specific Data AD Type
5-6    | 2      | 0x004C         | Company ID (Apple, little-endian)
7-8    | 2      | 0x1502         | **iBeacon Type (0x02) + Length (0x15=21 bytes)**
9-24   | 16     | UUID           | Proximity UUID (128-bit)
25-26  | 2      | Major          | Major value (big-endian)
27-28  | 2      | Minor          | Minor value (big-endian)
29     | 1      | Measured Power | RSSI at 1 meter (signed byte, 2's complement)

識別關鍵:scanRecord[5]==0x4C && scanRecord[6]==0x00 && scanRecord[7]==0x02 && scanRecord[8]==0x15 (Apple Company ID + iBeacon Type/Length)。

解析代碼實現

public class IBeaconParser {
    public static IBeacon fromScanData(byte[] scanRecord, int rssi) {
        if (scanRecord == null || scanRecord.length < 30) return null;
        // 檢查 Apple Company ID (0x004C little-endian)
        if (scanRecord[5] != (byte)0x4C || scanRecord[6] != (byte)0x00) return null;
        // 檢查 iBeacon Type/Length
        if (scanRecord[7] != (byte)0x02 || scanRecord[8] != (byte)0x15) return null;

        // 解析 UUID (16 bytes, offset 9)
        byte[] uuidBytes = Arrays.copyOfRange(scanRecord, 9, 25);
        String uuid = bytesToHex(uuidBytes); // 格式化為 8-4-4-4-12

        // Major/Minor (big-endian)
        int major = ((scanRecord[25] & 0xFF) << 8) | (scanRecord[26] & 0xFF);
        int minor = ((scanRecord[27] & 0xFF) << 8) | (scanRecord[28] & 0xFF);

        // Measured Power (signed)
        int txPower = (int) (byte) scanRecord[29];

        // 距離估算 (經驗公式)
        double ratio = rssi * 1.0 / txPower;
        double distance;
        if (ratio < 1.0) distance = Math.pow(ratio, 10);
        else distance = (0.89976 * Math.pow(ratio, 7.7095)) + 0.111;

        return new IBeacon(uuid, major, minor, txPower, rssi, distance);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(String.format("%02X", bytes[i]));
            if (i == 3 || i == 5 || i == 7 || i == 9) sb.append('-');
        }
        return sb.toString();
    }
}

class IBeacon {
    final String uuid; final int major; final int minor;
    final int txPower; final int rssi; final double distance;
    IBeacon(String uuid, int major, int minor, int txPower, int rssi, double distance) { ... }
    @Override public String toString() { return String.format("iBeacon[%s] Major:%d Minor:%d RSSI:%d Dist:%.2fm", uuid, major, minor, rssi, distance); }
}

掃描啟動 (Android 5.0+ 推薦 BluetoothLeScanner)

BluetoothLeScanner scanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
ScanSettings settings = new ScanSettings.Builder()
    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
    .setReportDelay(0) // 即時報告
    .build();
// 可選:過濾器限制 Manufacturer Data 前綴
List filters = Collections.singletonList(new ScanFilter.Builder()
    .setManufacturerData(0x004C, new byte[]{(byte)0x02, (byte)0x15}) // Apple + iBeacon prefix
    .build());

scanner.startScan(filters, settings, new ScanCallback() {
    @Override public void onScanResult(int callbackType, ScanResult result) {
        IBeacon beacon = IBeaconParser.fromScanData(result.getScanRecord().getBytes(), result.getRssi());
        if (beacon != null) Log.d(TAG, "Found: " + beacon);
    }
    @Override public void onBatchScanResults(List results) { /* 批次處理 */ }
    @Override public void onScanFailed(int errorCode) { Log.e(TAG, "Scan failed: " + errorCode); }
});

注意事項

  • UUID ≠ GATT Service UUID:iBeacon UUID 為廣播標識,用於區分部署項目/品牌;GATT UUID 用於連接後服務發現,兩者無關。
  • Tx Power 校準:廠商出廠測量 1 米 RSSI,實際環境差異大,距離估算僅供參考。
  • 後台掃描限制:Android 8.0+ 後台掃描頻率受限,前台服務 + 高優先級通知可維持高頻掃描。
  • Radius Networks android-ibeacon-service 開源庫已封裝完整解析、監控、區域進出事件,生產環境建議直接引用。
copyright © 萬盛學電腦網 all rights reserved