編輯:關於 Android 程式設計
接上一篇藍牙通信往下寫。這篇聚焦於低功耗藍牙(BLE)的完整鏈路:權限與藍牙狀態檢查、設備掃描、連接、notify 訂閱、讀寫數據,以及與硬件通信時繞不開的 CRC 校驗。
說明一下技術選型:動態權限部分用了 permissionsdispatcher 這個開源庫;掃描部分則選用了 BluetoothKit(github.com/dingjikerbo/BluetoothKit)。由於該庫沒有提供可直接 compile 的坐標,筆者把 module 上傳到了自建的 maven 私服,然後在其上做了一層薄封裝,讓業務代碼盡量遠離藍牙 API 細節。
動手掃描前,必須確認三件事:設備支持藍牙、藍牙已開啟、動態權限已授予。把這套判斷抽成接口和實現類,回調意圖就很清晰:
public interface IBluetoothInspectListener {
interface OnBluetoothCheckListener {
void onOpenBluetoothState(); // 已開啟,可以開始掃描
void onRefuseOpenBluetoothState(); // 用戶拒絕開啟
void unSupportBluetooth(); // 設備不支持
}
interface OnBluetoothInspectListener {
void onInspect();
void onSupportBluetooth();
boolean isOpenBluetooth();
void onOpenBluetooth();
}
}
public class OnBluetoothInspectListenerImpl implements IBluetoothInspectListener.OnBluetoothInspectListener {
private static final int REQUEST_ENABLE_BT = 1;
private static OnBluetoothInspectListenerImpl instance;
private OnBluetoothCheckListener onBluetoothCheckListener;
BluetoothAdapter mBluetoothAdapter;
Activity mContext;
private OnBluetoothInspectListenerImpl(Activity mContext, OnBluetoothCheckListener l) {
this.mContext = mContext;
this.onBluetoothCheckListener = l;
this.mBluetoothAdapter =
((BluetoothManager) mContext.getSystemService("bluetooth")).getAdapter();
}
public static OnBluetoothInspectListenerImpl init(Activity a, OnBluetoothCheckListener l) {
instance = new OnBluetoothInspectListenerImpl(a, l);
return instance;
}
public void onInspect() {
if (mBluetoothAdapter == null) onBluetoothCheckListener.unSupportBluetooth();
else onSupportBluetooth();
}
public void onSupportBluetooth() {
if (isOpenBluetooth()) onBluetoothCheckListener.onOpenBluetoothState();
else onOpenBluetooth();
}
public boolean isOpenBluetooth() { return mBluetoothAdapter.isEnabled(); }
public void onOpenBluetooth() {
mContext.startActivityForResult(
new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), REQUEST_ENABLE_BT);
}
// 在 Activity.onActivityResult 中轉交
public void performResult(int requestCode, int resultCode) {
if (requestCode != REQUEST_ENABLE_BT || onBluetoothCheckListener == null) return;
if (isOpenBluetooth()) onBluetoothCheckListener.onOpenBluetoothState();
else onBluetoothCheckListener.onRefuseOpenBluetoothState();
}
}
Activity 側的接入非常輕量:拿到動態權限後調一次 onInspect(),然後在 onActivityResult 裡把結果轉交給 performResult。一旦 onOpenBluetoothState 被回調,就可以放心開始掃描。
把能力定義成接口,便於替換實現與 mock 測試:
public interface IBluetoothListener {
void startScan();
void stopScan();
void connect();
void read();
void write();
void registerNotify();
void unRegisterNotify();
void disconnect();
void release();
}
public interface BluetoothCallback {
void showInformation(String information);
void toastMessage(String message);
void readResponse(byte[] bytes);
}
這是整篇最需要強調的一句:Service UUID 和特徵 UUID 不能隨便抄別人的。不同硬件模塊的 GATT 服務定義不同,UUID 不匹配的結果是連接成功但讀寫全部失敗。務必向硬件工程師索取:
public static final UUID SERVICE_UUID = /* 硬件提供 */; public static final UUID WRITE_CHARA = /* 硬件提供 */; public static final UUID READ_CHARA = /* 硬件提供 */;
BluetoothKit 的 SearchRequest 支持分段配置掃描策略:先掃 3 秒 BLE、再掃 5 秒經典藍牙、最後再補 2 秒 BLE。這種「分段掃描」在設備處於不同廣播狀態時命中率更高。
request = new SearchRequest.Builder()
.searchBluetoothLeDevice(3000, 1) // 先掃 3000ms,3 次
.searchBluetoothClassicDevice(5000) // 再掃經典藍牙 5000ms
.searchBluetoothLeDevice(2000) // 最後補掃 2000ms
.build();
@Override
public void startScan() {
mClient.search(request, new SearchResponse() {
@Override public void onSearchStarted() {}
@Override public void onDeviceFounded(SearchResult device) {
if (device.device.getAddress().equals(deviceMac) && !isStopScan) {
isStopScan = true; // 找到目標立即停止掃描
currentBluetoothDevice = device.device;
connect();
stopScan();
}
}
@Override public void onSearchStopped() {
if (currentBluetoothDevice == null) callback.toastMessage("沒有發現匹配的設備");
}
@Override public void onSearchCanceled() {}
});
}
@Override
public void connect() {
mClient.connect(deviceMac, new BleConnectResponse() {
@Override public void onResponse(int code, Bundle data) {
if (code == REQUEST_SUCCESS) {
callback.showInformation("連接成功");
registerNotify(); // 連接成功後訂閱通知
} else {
release();
callback.toastMessage("連接失敗");
}
}
});
}
一個實踐細節:掃描到目標設備後要立刻置標誌停止後續回調,否則同一設備會被反覆「發現」,導致重複連接。
@Override
public void registerNotify() {
mClient.notify(deviceMac, SERVICE_UUID, READ_CHARA, new BleNotifyResponse() {
@Override public void onNotify(UUID service, UUID character, byte[] value) {
callback.readResponse(value); // 硬件主動上報
}
@Override public void onResponse(int code) {
if (code == REQUEST_SUCCESS) {
callback.showInformation("數據已發送,等待數據響應");
} else {
release();
callback.toastMessage("發送失敗,請再試一次");
}
}
});
}
@Override
public void write() {
mClient.write(deviceMac, SERVICE_UUID, WRITE_CHARA, bytes, new BleWriteResponse() {
@Override public void onResponse(int code) {
if (code != REQUEST_SUCCESS) {
release();
callback.toastMessage("發送數據失敗");
}
}
});
}
這裡只討論 notify 模式接收數據,read 主動讀取在實際項目中用得較少,可按需實現。另外要注意:部分手機對單次發送的字節上限有限制(常見為 20 字節),數據超長時必須自行分包並在協議層處理粘包。
BLE 一次 notify 回傳的字節數有限,一條完整協議幀往往需要多次回調才能收齊。最簡單的做法是維護一個偏移量和目標緩衝區:
@Override
public void readResponse(byte[] bytes) {
saveBytes(bytes, responseBytes);
if (readCount == responseBytes.length) {
onResponseReadResult(responseBytes); // 收齊後再解析
}
}
public void saveBytes(byte[] src, byte[] ds) {
for (int i = 0; i < src.length; i++) {
ds[i + readCount] = src[i];
}
readCount += src.length;
}
更健壮的方案是在協議裡定義幀頭、長度字段和結束標誌,用狀態機解析。上面這種「已知總長」的做法只適用於協議本身就確定性長度的場景。
和硬件通信幾乎一定會用到 CRC8 / CRC16。硬件側通常寫 C,直接拷到 Java 裡容易出問題——因爲 C 的 char 表現和 Java 的 byte 有符號差異,查表法中的數組必須顯式轉成 byte。
public class Crc8Helper {
// 查表法: precomputed 256 項表通常直接由硬件側提供
static byte[] crc8_tab = { /* 0x00, 0x5E, 0xBC, ... 共 256 項 */ };
/** 計算整個數組的 CRC8 */
public static byte calcCrc8(byte[] data) {
return calcCrc8(data, 0, data.length, (byte) 0);
}
/** 指定區間的 CRC8 */
public static byte calcCrc8(byte[] data, int offset, int len, byte preval) {
byte ret = preval;
for (int i = offset; i < (offset + len); ++i) {
ret = crc8_tab[0x00ff & (ret ^ data[i])];
}
return ret;
}
}
兩個關鍵點:查表時用 0x00ff & (ret ^ data[i]) 做掩碼,因爲異或結果在 Java 中可能為負,直接當下標會數組越界;preval 參數支持分片累加校驗,大數據分包發送時不必從頭重算。
藍牙開發的痛點集中在三處:一是版本適配,Android 4.4 與 5.1 以上的行為差異明顯,動態權限也是 6.0 之後才有的課題;二是協議對齊,UUID、字節序、CRC 算法必須和硬件嚴格一致;三是收發邊界,分包、粘包、超時重試都要在應用層自己兜住。
無論是自己直接寫 API 還是引入第三方框架,這幾件事都躲不掉。把掃描、連接、讀寫各自封裝成回調清晰的接口,再配合日誌把每一步狀態打出來,調試效率會高很多。
Android 多媒體:四步快速掌握 SoundPool 播放音效
在 Android 中,短提示音、按鈕音與遊戲音效通常不建議用 MediaPlayer,而是使用更輕量的 SoundPool。 建立 SoundPool API 21 以
屬性動畫與補間動畫總結
Android 動畫體系中,常見的兩大類別是補間動畫與屬性動畫。補間動畫出現較早,主要用於 View 的視覺變換;屬性動畫則在 Android 3.0 之後推出,能更真實
Android 之 Intent 使用全解析
本文涵蓋:Intent 簡介、Intent 物件的組成、顯式 Intent 與隱式 Intent 的區別與用法。 Intent 簡介 Intent 主要用於元件之間的跳轉
Android 登入註冊介面開發與使用者資訊管理完整實作詳解
剛開始學 Android 時寫的第一個小專案,功能是登入、註冊、註銷、修改密碼、記住密碼這五個基本操作,涵蓋的知識點有三塊: 1. Button、TextView、Edi