Android 经典蓝牙和低功耗蓝牙扫描

在现代智能手机应用程序中,蓝牙技术是实现设备间无线通信的重要手段。Android平台支持两种主要的蓝牙技术:经典蓝牙(Classic Bluetooth)和低功耗蓝牙(Bluetooth Low Energy, BLE)。本文将探讨如何在Android中扫描这两种蓝牙设备,并提供相应的代码示例。

蓝牙基础知识

经典蓝牙

经典蓝牙是一种适用于数据传输速率高、功耗不敏感的应用场景,通常用于音频设备、打印机等。

低功耗蓝牙

低功耗蓝牙则专为物联网(IoT)设备而设计,适用于传输少量数据且对电池寿命要求高的应用,比如健康监测设备、智能家居装备等。

Android蓝牙扫描的基本步骤

权限设置

在Manifest文件中,需要声明使用蓝牙和位置权限。

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

经典蓝牙扫描示例

以下是经典蓝牙设备扫描的基本代码示例:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null && !bluetoothAdapter.isDiscovering()) {
    bluetoothAdapter.startDiscovery();
}
BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 处理找到的设备
            Log.i("BluetoothDevice", "Found device: " + device.getName() + " [" + device.getAddress() + "]");
        }
    }
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);

低功耗蓝牙扫描示例

相比经典蓝牙, BLE 的扫描更加高效和简单。下面是 BLE 设备扫描的代码示例:

BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
ScanCallback scanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        super.onScanResult(callbackType, result);
        BluetoothDevice device = result.getDevice();
        // 处理找到的 BLE 设备
        Log.i("BLEDevice", "Found device: " + device.getName() + " [" + device.getAddress() + "]");
    }
};

bluetoothLeScanner.startScan(scanCallback);

类图展示

以下是蓝牙扫描相关类的简单类图,描述了经典蓝牙和低功耗蓝牙的主要类之间的关系:

classDiagram
    class BluetoothScanner {
        +startDiscovery()
        +stopDiscovery()
        +startScan()
        +stopScan()
    }
    class ClassicBluetoothScanner {
        +onDeviceFound()
    }
    class BLEScanner {
        +onScanResult()
    }

    BluetoothScanner <|-- ClassicBluetoothScanner
    BluetoothScanner <|-- BLEScanner

权限与设备功能

权限名称 描述
BLUETOOTH 允许应用使用蓝牙
BLUETOOTH_ADMIN 允许应用管理蓝牙设备
ACCESS_FINE_LOCATION 允许应用获取位置信息 (扫描BLE设备时需要)

结论

通过以上示例,我们可以看到在Android平台上实现蓝牙设备的扫描是相对简单的任务。经典蓝牙适用于需要传输大量数据的场景,而低功耗蓝牙则是在IoT设备和应用中广泛应用的选择。根据使用场景的不同,开发者可以选择合适的蓝牙技术来满足应用需求。

无论您是开发音频设备、健康监测器,还是智能家居产品,掌握蓝牙的基本用法都是必不可少的。当您实现蓝牙功能时,请务必谨慎处理各类权限,并合理设计用户体验。希望本文对您在蓝牙开发方面有所帮助!