在Android 12中,需要使用新方法启用BLE扫描权限。要实现此功能,可以使用以下示例代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { Intent bleScanIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE_BLE_SCAN); startActivityForResult(bleScanIntent, REQUEST_BLE_SCAN_PERMISSION); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_BLE_SCAN_PERMISSION) { if (resultCode == Activity.RESULT_OK) { // Permission was granted, start BLE scan startBleScan(); } else { // Permission denied, show error message or do something else } } else { super.onActivityResult(requestCode, resultCode, data); } }
private void startBleScan() { BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothLeScanner scanner = bluetoothManager.getAdapter().getBluetoothLeScanner();
ScanSettings settings = new ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build();
List
scanner.startScan(filters, settings, scanCallback); }
private ScanCallback scanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result);
BluetoothDevice device = result.getDevice();
// handle scanned device...
}