如要尋找 BLE 裝置,請使用
startScan()
敬上
方法。這個方法需要
ScanCallback
做為參數。
您必須實作這個回呼,因為這就是掃描結果傳回的方式。
由於掃描會耗用大量電力,因此請留意下列事項
規範:
- 找到需要的裝置後,請立即停止掃描。
- 絕不掃描迴圈,並且一律設定掃描時間限制。符合以下條件的裝置 可能已超出範圍,會繼續掃描 會消耗電量
在以下範例中,BLE 應用程式提供一項活動
(DeviceScanActivity
) 掃描可用的藍牙 LE 裝置和螢幕
要提供給使用者的清單下列程式碼片段說明如何開始及停止
掃描:
Kotlin
private val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner private var scanning = false private val handler = Handler() // Stops scanning after 10 seconds. private val SCAN_PERIOD: Long = 10000 private fun scanLeDevice() { if (!scanning) { // Stops scanning after a pre-defined scan period. handler.postDelayed({ scanning = false bluetoothLeScanner.stopScan(leScanCallback) }, SCAN_PERIOD) scanning = true bluetoothLeScanner.startScan(leScanCallback) } else { scanning = false bluetoothLeScanner.stopScan(leScanCallback) } }
Java
private BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner(); private boolean scanning; private Handler handler = new Handler(); // Stops scanning after 10 seconds. private static final long SCAN_PERIOD = 10000; private void scanLeDevice() { if (!scanning) { // Stops scanning after a predefined scan period. handler.postDelayed(new Runnable() { @Override public void run() { scanning = false; bluetoothLeScanner.stopScan(leScanCallback); } }, SCAN_PERIOD); scanning = true; bluetoothLeScanner.startScan(leScanCallback); } else { scanning = false; bluetoothLeScanner.stopScan(leScanCallback); } }
如果只要掃描特定類型的周邊裝置,可以改為呼叫:
startScan(List<ScanFilter>, ScanSettings, ScanCallback)
、
提供 ScanFilter
清單
限制掃描範圍的裝置
ScanSettings
物件,該物件
指定掃描作業的相關參數。
以下程式碼範例是
ScanCallback
、
也就是提供 BLE 掃描結果的介面找到結果後
這些程式碼會新增到 DeviceScanActivity
的清單轉接器,以供
內容。
Kotlin
private val leDeviceListAdapter = LeDeviceListAdapter() // Device scan callback. private val leScanCallback: ScanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { super.onScanResult(callbackType, result) leDeviceListAdapter.addDevice(result.device) leDeviceListAdapter.notifyDataSetChanged() } }
Java
private LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter(); // Device scan callback. private ScanCallback leScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); leDeviceListAdapter.addDevice(result.getDevice()); leDeviceListAdapter.notifyDataSetChanged(); } };