編輯:關於 Android 程式設計
本文以 april beacon 這個模組為例,說明如何從 BLE 掃描結果中拆解出 iBeacon 的三個關鍵欄位,並進一步估算距離。至於 iBeacon 是什麼、應用場景為何,這裡不再贅述。
一個 april beacon 送出的原始資料如下:
0201061AFF4C0002159069BDB88C11416BAC3F33468C2788A3044B0378C60C09417072696C426561636F6E051250002003020A0000000000000000000000
逐段解讀:
02 Number of bytes that follow in first AD structure
01 Flags AD type
06 Flags value = 0x1A = 000011010
bit 0 (OFF) LE Limited Discoverable Mode
bit 1 (ON) LE General Discoverable Mode
bit 2 (OFF) BR/EDR Not Supported
bit 3 (ON) Simultaneous LE and BR/EDR (controller)
bit 4 (ON) Simultaneous LE and BR/EDR (host)
1a Number of bytes that follow in second (and last) AD structure
—— 以下為裝置特定資料(Manufacture Data)——
ff 代表後面是 Manufacture Data
4c 00 公司識別碼 0x4C00,即 Apple
(https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers)
02 iBeacon 標識位
15 後續 22 個位元組的長度(uuid + major + minor 之總和)
90 69 bd b8 8c 11 41 6b ac 3f 33 46 8c 27 88 a3 Proximity UUID
04 4b major = 1099
03 78 minor = 888
c6 txPower,為補碼形式,轉原碼即 -58
0c 09 未知
41 70 72 69 6c 42 65 61 63 6f 6e "AprilBeacon" 的十六進位
05 12 50 00 20 03 02 0a 00 ... 未知
txPower 的補碼換算:C6 = 1100 0110 → 反碼 1100 0101 → 原碼 1011 1010,即 −(32+16+8+2) = −58。
Proximity UUID:用來把自己的 beacon 群組與其他家的裝置區分開。舉例來說,店家若在某一區擺放多個 beacon 形成一條「服務帶」,屬於同一條服務帶的 beacon 就會分配到相同的 Proximity UUID;為這條服務帶設計的 App,就能在背景中靠這個 UUID 掃出整組裝置。
Major:把相關的 beacon 歸為一組。例如同一家分店的所有 beacon 共用一個 major,App 便能判斷使用者目前身在哪家店。
Minor:標識單一 beacon 裝置。同一家店內每顆 beacon 的 minor 都不同,如此才能定位使用者站在店內哪個位置。
最後一個欄位 txPower 用來判斷你與 beacon 的距離遠近。透過它,可以得到粗略的分級(靠近/遠離/不在範圍內),也能換算成以公尺為單位的估算距離。
原理是這樣的:txPower(本例為 0xC6,換算後為 −58 dBm)代表距離裝置 1 公尺時測得的訊號強度,也就是 RSSI(Received Signal Strength Indication)。如果當下的 RSSI 比這個基準值弱,代表你正在遠離。只要同時握有「1 公尺處的 RSSI」與「目前的 RSSI」,就能推算出當前距離。iOS 已內建此功能,其他平台則需自行實作。
protected static double calculateAccuracy(int txPower, double rssi) {
if (rssi == 0) {
return -1.0; // 無法判定時回傳 -1
}
double ratio = rssi * 1.0 / txPower;
if (ratio < 1.0) {
return Math.pow(ratio, 10);
} else {
return (0.89976) * Math.pow(ratio, 7.7095) + 0.111;
}
}
使用藍牙需要下列權限:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
掃描的關鍵程式碼:
package cn.edu.zafu.ble;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 1);
}
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
final byte[] scanRecord) {
int startByte = 2;
boolean patternFound = false;
// 尋找 iBeacon 的資料型態標記
while (startByte <= 5) {
if (((int) scanRecord[startByte + 2] & 0xff) == 0x02
&& ((int) scanRecord[startByte + 3] & 0xff) == 0x15) {
patternFound = true;
break;
}
startByte++;
}
if (patternFound) {
// 取出 16 位元組的 UUID
byte[] uuidBytes = new byte[16];
System.arraycopy(scanRecord, startByte + 4, uuidBytes, 0, 16);
String hexString = bytesToHex(uuidBytes);
String uuid = hexString.substring(0, 8) + "-"
+ hexString.substring(8, 12) + "-"
+ hexString.substring(12, 16) + "-"
+ hexString.substring(16, 20) + "-"
+ hexString.substring(20, 32);
int major = (scanRecord[startByte + 20] & 0xff) * 0x100
+ (scanRecord[startByte + 21] & 0xff);
int minor = (scanRecord[startByte + 22] & 0xff) * 0x100
+ (scanRecord[startByte + 23] & 0xff);
String ibeaconName = device.getName();
String mac = device.getAddress();
int txPower = (scanRecord[startByte + 24]);
Log.d("BLE", bytesToHex(scanRecord));
Log.d("BLE", "Name:" + ibeaconName
+ "\nMac:" + mac
+ " \nUUID:" + uuid
+ "\nMajor:" + major
+ "\nMinor:" + minor
+ "\nTxPower:" + txPower
+ "\nrssi:" + rssi);
Log.d("BLE", "distance:" + calculateAccuracy(txPower, rssi));
}
}
};
static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
protected static double calculateAccuracy(int txPower, double rssi) {
if (rssi == 0) {
return -1.0;
}
double ratio = rssi * 1.0 / txPower;
if (ratio < 1.0) {
return Math.pow(ratio, 10);
} else {
return (0.89976) * Math.pow(ratio, 7.7095) + 0.111;
}
}
}
本文所謂的「初步」,就是能把 iBeacon 模組的基本資訊讀出來。但有幾點在真實專案中勢必會遇到。
首先是距離估算的精度。calculateAccuracy 算出來的是「米數」,但 BLE 訊號极易受遮蔽、多墓碑與人體影響,實測波動常常達到數公尺。這個值適合拿來判斷「靠近/遠離」這類相對關係,不適合當成精確定位使用;若要做平滑,通常需要搭配移動平均或濾波演算法。
其次是 API 版本問題。startLeScan 在 Android 5.0 之後已被標記為 deprecated,官方建議改用 BluetoothLeScanner 搭配 ScanFilter 與 ScanSettings,掃描的功耗與可控性都更好。同時,Android 6.0 起 BLE 掃描需要動態申請位置權限,Android 12 以上則改為 BLUETOOTH_SCAN 這類新權限,僅宣告 BLUETOOTH 與 BLUETOOTH_ADMIN 是不足夠的。
最後,onLeScan 是在背景執行緒上被呼叫的,若要在其中直接更新 UI,仍需透過 Handler 或 runOnUiThread 切回主執行緒。而 startLeScan 啟動後也別忘了在不需要時呼叫 stopLeScan,否則持續掃描會明顯拉高電耗。
Android 實現局部界面動態切換的方法
本文介紹如何實現「局部界面固定、局部界面動態切換」的效果,供大家參考。效果如下: 這個效果由 3 個 layout 構成。 main.xml: <?
Android VideoView 播放視頻完整教學
VideoView 是什麼VideoView 是 Android 提供的視頻播放元件,使用方式與 ImageView 類似。ImageView 負責顯示圖片,而 Vide
模仿知乎回答詳情頁動畫:屬性動畫實現標題欄自動隱藏與工具欄浮現
本篇示範如何還原「知乎」回答詳情頁的滾動動畫:內容向上滑時頂部的標題欄與問題標題往上收起,底部的工具列同時浮現;反向滑動時則全部復位。這個效果不需要任何第三方庫,只用屬性
Android 接入微信分享功能完整實作與注意事項
一、取得官方文件並下載開發資源 第一步是前往微信開放平台(https://open.weixin.qq.com/)。若你還沒有帳號,請先完成註冊,並填寫、上傳開發者資料,