優化Android搜尋藍牙裝置方式(API 21)
Android 6.0(API 21)以後, 搜尋藍芽裝置的方式改成:
BluetoothAdapter.startScan (ScanCallback callback)
這種方式我一直用了很久, 也沒遇到問題.
直到有一個需求是隨時監控廣播封包,
這種寫法就會遇到問題, 無法快速取得周遭藍牙廣播資料, 因此需要修改寫法, 把能下的藥都下下去(但耗電):
final List<ScanFilter> filters = new ArrayList<>(); ScanFilter filter = new ScanFilter.Builder().build(); filters.add(filter); final ScanSettings scanSettings = new ScanSettings.Builder() .setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT).setMatchMode(ScanSettings.MATCH_MODE_STICKY).setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); BluetoothAdapter.getBluetoothLeScanner().startScan(filters,scanSettings,mLeScanCallback);