Android 低功耗蓝牙连接和配对

简介

在 Android 开发中,低功耗蓝牙(Low Energy Bluetooth)是一项重要的功能。本文将介绍如何实现 Android 低功耗蓝牙连接和配对的流程和代码实现。

流程

下面是实现 Android 低功耗蓝牙连接和配对的整个流程,以表格形式展示:

步骤 描述
1 检查设备是否支持低功耗蓝牙
2 打开蓝牙适配器
3 扫描并获取设备列表
4 选择目标设备
5 连接目标设备
6 配对目标设备
7 传输数据

代码实现

下面将逐步介绍每一步需要做什么,并给出相应的代码实现。

步骤 1:检查设备是否支持低功耗蓝牙

在开始使用低功耗蓝牙之前,需要检查设备是否支持该功能。可以在 onCreate() 方法中添加以下代码:

// 检查设备是否支持低功耗蓝牙
private boolean isBluetoothLESupported() {
    return getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}

这段代码通过调用 hasSystemFeature() 方法来检查设备是否支持低功耗蓝牙。

步骤 2:打开蓝牙适配器

在开始使用低功耗蓝牙之前,需要先打开蓝牙适配器。可以在 onCreate() 方法中添加以下代码:

private BluetoothAdapter mBluetoothAdapter;

// 打开蓝牙适配器
private void enableBluetooth() {
    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
    
    // 检查蓝牙是否已经打开
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}

这段代码通过获取 BluetoothManager 实例,并调用 getAdapter() 方法来获取蓝牙适配器。然后,通过判断蓝牙适配器是否为 null 或者未启用来决定是否需要请求用户打开蓝牙。

步骤 3:扫描并获取设备列表

在开始连接和配对设备之前,需要先扫描并获取设备列表。可以添加以下代码:

private List<BluetoothDevice> mDeviceList = new ArrayList<>();

// 扫描并获取设备列表
private void scanDevices() {
    mBluetoothAdapter.startLeScan(mLeScanCallback);
}

// 扫描回调
private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDeviceList.add(device);
                    }
                });
            }
        };

这段代码通过调用 startLeScan() 方法来开始扫描设备。扫描回调函数 onLeScan() 会在扫描到设备时被调用,并将设备添加到设备列表中。

步骤 4:选择目标设备

在设备列表中选择目标设备。可以根据自己的需求,在界面中提供一个设备列表供用户选择。

步骤 5:连接目标设备

选择目标设备后,需要连接该设备。可以添加以下代码:

private BluetoothGatt mBluetoothGatt;

// 连接目标设备
private boolean connectDevice(BluetoothDevice device) {
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    return mBluetoothGatt != null;
}

// GATT 回调
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,