編輯:關於 Android 程式設計
iBeacon 的工作原理建立在 Bluetooth Low Energy(BLE,低功耗藍牙)之上。iBeacon 基站會持續向四周廣播音訊號,當行動裝置進入其覆蓋範圍時就能接收到。由於這是一項開放技術標準,任何符合規範的裝置都能使用,Android 自然也不例外——Google 從 Android 4.3 開始支援 BLE。
定位一直是極關鍵的能力。透過部署 iBeacon 基站可以實現室內導航,同時也能推送訊息,在百貨零售、體育館、博物館等場景中能帶來很不錯的體驗。加上藍牙本身傳輸距離足、功耗低、支援訊號加密,iBeacon 在行動支付領域也頗具想像空間。
BLE(又稱 Bluetooth Smart)最早可追溯到 Nokia 在 2006 年提出的 Wibree,後來併入藍牙標準,成為 Bluetooth 4.0 的一部分。目前市面上常見三類藍牙裝置:

BLE 相比傳統藍牙最大的優勢是功耗降低約九成,同時傳輸距離更長(可超過 100 公尺),並在安全性與穩定性上有所提升(支援 AES 加密與 CRC 驗證)。
iBeacon 本身還有幾個特點:
基站透過廣播通道持續對外發送位置資訊,發送頻率越高越耗電。要注意的是,iBeacon 本身並不推送訊息,它只用於定位;推播功能必須由 App 自行實作。Apple 定義了其中 32 位元的廣播資料格式:

UUID + Major + Minor 三者共同構成一個 Beacon 的唯一識別,概念上有點類似網路上的 IP 位址加埠號。TX Power 則是測距依據,iBeacon 目前只定義了三個粗略等級:
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() 中確保釋放。
用 ListView 打造自定義表格(三):加入列合併能力
在前兩篇的基礎上,我把自定義表格又往前推了一步——現在它支援「列合併」了。整體架構拆成兩種模式:簡單模式與複雜模式,開發者可依場景自由挑選。 兩種模式的分野 簡單模式:
Android 各種對話框總結筆記:從 AlertDialog 到自定義樣式
對話框是 Android 中最常被使用、也最容易被寫得雜亂的元件。以下把常見的幾種類型整理成一份可直接複製的筆記。 一、確定/取消對話框(帶圖示) // 參數:上下文、主
Android 開發第六彈:動手做一個簡易時鐘與計時器
接續上一篇的簡易時鐘(鬧鐘)。這次做時鐘與計時器,外觀一樣樸素,但功能齊全。 時鐘 先從最簡單的時鐘開始。顯示目前時間而已,若要換成世界各城市的時間,也只是在小時上加减
Android ListView 下拉刷新、上拉加載與多欄橫向滾動整合實作
ListView 是 Android 最常被使用的清單控制項,可以搭配不同的檢視模式呈現大圖示、小圖示、清單或報表。實際專案裡,「下拉刷新+上拉加載」幾乎是標配;而如果資