1. 藍(lán)牙相關(guān)權(quán)限(GPS)要先于BluetoothAdapter獲取
我的所有藍(lán)牙處理都放在一個(gè)Helper里,因此在Application里,我初始化了BluetoothAdapter,當(dāng)權(quán)限未授予時(shí)厕妖,我授予權(quán)限后,搜索藍(lán)牙則收不到藍(lán)牙廣播;于是我想著在權(quán)限打開(kāi)后雁佳,重新初始化BluetoothAdapter試試,結(jié)果發(fā)現(xiàn)也不行同云;BluetoothAdapter只能在權(quán)限滿足后再初始化才有效糖权;
2. 弱機(jī)型的適配;
有一些機(jī)型的藍(lán)牙芯片非常差炸站,比如三星的A7;差主要體現(xiàn)在剛連接后星澳,發(fā)送指令容易失敗,于是做了一套檢測(cè)機(jī)制來(lái)避免這個(gè)問(wèn)題
BluetoothHelper.getInstance().connectBluetooth(address, (gatt, connect) -> {
//收到成功回調(diào)時(shí)武契,開(kāi)始檢測(cè)
if (connect) {
startCheck();
}
});
startCheck()
public void startCheck() {
SUtils.saveBooleanData(context, SharePreConstant.CHECK_STABLE_SUC + address, false);
sendCheck();
}
在onServicesDiscovered回調(diào)后募判,存儲(chǔ) (SharePreConstant.CHECK_STABLE_SUC + address)的狀態(tài)荡含;如果為true,則發(fā)送指令:
private void sendCheck() {
boolean isBleStable = SUtils.getBooleanData(BaseApplication.getContext(), SharePreConstant.CHECK_BLE_STABLE_SUC + address);
//弱藍(lán)牙芯片遲遲不給service回調(diào)届垫,沒(méi)辦法释液,只能斷開(kāi)重新連接
if (!isBleStable) {
tryCount++;
if (tryCount > 5) {
tryCount = 0;
BluetoothHelper.getInstance().disconnectBle(true, address);
safeConnect();
return;
}
Logs.i("藍(lán)牙還沒(méi)有就緒");
myHandler.postDelayed(() -> sendCheck(), 500);
return;
}
Logs.i("藍(lán)牙已經(jīng)就緒");
SUtils.saveBooleanData(BaseApplication.getContext(), SharePreConstant.CHECK_BLE_STABLE_SUC + address, false);
//如果當(dāng)前藍(lán)牙不在dfu狀態(tài)下則發(fā)送驗(yàn)證指令,我把獲取電量當(dāng)作驗(yàn)證與心跳指令
if (!BluetoothHelper.getInstance().checkDfu(bluetoothGatt.getDevice().getName())) {
myHandler.postDelayed(() -> {
Logs.empty();
byte[] checkBattery = {BleCommand.GET_BATTERY};
BluetoothHelper.getInstance().writeCharacteristicByAddress(checkBattery, address, true);
checkSuc();
}, 200);
}
}
當(dāng)藍(lán)牙返回BleCommand.GET_BATTERY的值時(shí)装处,則判斷為成功:
/**
* 檢查是否成功
*/
private void checkSuc() {
boolean isChecked = SUtils.getBooleanData(context, SharePreConstant.CHECK_STABLE_SUC + address);
if (isChecked) {
myHandler.sendEmptyMessageDelayed(MSG_CANCEL_DIALOG, 300);
myHandler.sendEmptyMessageDelayed(MSG_BLE_CONNECTED, 500);
} else {
tryCount++;
//如果多次未收到消息误债,則斷開(kāi),重新連接
if (tryCount > 5) {
tryCount = 0;
BluetoothHelper.getInstance().disconnectBle(true, address);
safeConnect();
return;
}
sendCheck();
}
}
藍(lán)牙app外包請(qǐng)找我:505709544