Android 蓝牙扫描实现步骤

流程概述

在实现 Android 蓝牙扫描功能之前,我们需要先了解整个流程。下面是实现蓝牙扫描的基本步骤:

步骤 动作
1 初始化蓝牙适配器
2 检查蓝牙权限
3 检查蓝牙是否打开
4 注册广播接收器
5 扫描蓝牙设备
6 处理扫描结果
7 停止扫描

接下来,我们将逐步解释每个步骤应该采取的行动,并提供相应的代码示例。

1. 初始化蓝牙适配器

在开始进行蓝牙扫描之前,我们需要初始化蓝牙适配器。蓝牙适配器是与蓝牙硬件交互的主要接口。以下是初始化蓝牙适配器的代码示例:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

2. 检查蓝牙权限

在 AndroidManifest.xml 文件中,我们需要添加相应的权限声明以允许我们使用蓝牙功能。以下是一个示例:

<manifest xmlns:android="
    package="com.example.bluetooth">

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

    ...

</manifest>

3. 检查蓝牙是否打开

在进行蓝牙扫描之前,我们需要检查蓝牙是否已经打开。如果蓝牙未打开,我们可以请求用户打开蓝牙。以下是一个示例:

if (!bluetoothAdapter.isEnabled()) {
    Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH);
}

4. 注册广播接收器

在进行蓝牙扫描之前,我们需要注册一个广播接收器来接收扫描结果和其他蓝牙事件。以下是一个示例:

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            // 扫描开始
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // 发现蓝牙设备
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 处理设备
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            // 扫描结束
        }
    }
};

...

IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(broadcastReceiver, filter);

5. 扫描蓝牙设备

一旦我们完成了前面的准备工作,就可以开始扫描蓝牙设备了。以下是一个示例:

bluetoothAdapter.startDiscovery();

6. 处理扫描结果

在接收到蓝牙设备的扫描结果后,我们需要对其进行处理。可以将设备的名称和地址显示在界面上,或者执行其他自定义操作。以下是一个示例:

@Override
public void onReceive(Context context, Intent intent) {
    ...
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        String deviceName = device.getName();
        String deviceAddress = device.getAddress();
        // 处理设备,例如显示在列表中
    }
    ...
}

7. 停止扫描

当我们完成扫描或需要停止扫描时,我们可以调用 cancelDiscovery() 方法停止扫描。以下是一个示例:

bluetoothAdapter.cancelDiscovery();

以上是实现 Android 蓝牙扫描的基本步骤和相