Android提供了一个`android.bluetooth.le` 包来支持 Bluetooth 低功耗

Android提供了一个android.bluetooth.le 包来支持 Bluetooth 低功耗。该包中的类和接口支持 Bluetooth 低功耗广告、扫描、连接和数据传输。在 Kotlin 和 Java 中,您可以使用 BluetoothLeScanner 类扫描设备,使用 BluetoothGatt 类与设备连接,并使用 BluetoothGattCharacteristic 类管理数据传输。例如,在 Kotlin 中扫描设备的示例代码如下所示:

val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
    val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    bluetoothManager.adapter
}

val scanner: BluetoothLeScanner? = bluetoothAdapter?.bluetoothLeScanner

val scanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult?) {
        // 处理扫描结果
    }
}

// 扫描设备
scanner?.startScan(scanCallback)

连接设备的示例代码如下所示:

private var bluetoothGatt: BluetoothGatt? = null
private val gattCallback = object : BluetoothGattCallback() {
    override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
        // 处理连接状态变化
    }

    override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
        // 处理服务发现
    }

    override fun onCharacteristicRead(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
        // 处理读取特征值操作的响应
    }

    override fun onCharacteristicWrite(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
        // 处理写入特征值操作的响应
    }
}

// 连接设备
bluetoothGatt = device.connectGatt(context, false, gattCallback)

android.bluetooth.le Kotlin |Java
Classes
AdvertiseCallback Bluetooth LE advertising callbacks, used to deliver advertising operation status.
AdvertiseData Advertise data packet container for Bluetooth LE advertising.
AdvertiseData.Builder Builder for AdvertiseData.
AdvertiseSettings The AdvertiseSettings provide a way to adjust advertising preferences for each Bluetooth LE advertisement instance.
AdvertiseSettings.Builder Builder class for AdvertiseSettings.
AdvertisingSet This class provides a way to control single Bluetooth LE advertising instance.
AdvertisingSetCallback Bluetooth LE advertising set callbacks, used to deliver advertising operation status.
AdvertisingSetParameters The AdvertisingSetParameters provide a way to adjust advertising preferences for each Bluetooth LE advertising set.
AdvertisingSetParameters.Builder Builder class for AdvertisingSetParameters.
BluetoothLeAdvertiser This class provides a way to perform Bluetooth LE advertise operations, such as starting and stopping advertising.
BluetoothLeScanner This class provides methods to perform scan related operations for Bluetooth LE devices.
PeriodicAdvertisingParameters The PeriodicAdvertisingParameters provide a way to adjust periodic advertising preferences for each Bluetooth LE advertising set.
PeriodicAdvertisingParameters.Builder
ScanCallback Bluetooth LE scan callbacks.
ScanFilter Criteria for filtering result from Bluetooth LE scans.
ScanFilter.Builder Builder class for ScanFilter.
ScanRecord Represents a scan record from Bluetooth LE scan.
ScanResult ScanResult for Bluetooth LE scan.
ScanSettings Bluetooth LE scan settings are passed to BluetoothLeScanner#startScan to define the parameters for the scan.
ScanSettings.Builder Builder for ScanSettings.
为了使用 BluetoothGattCharacteristic 对蓝牙设备进行数据的读写操作,首先需要进行连接和服务发现操作,然后才能对相应的特性进行读写。接下来分别介绍读和写的操作方法:

  1. 读取数据
    在已连接蓝牙设备的 onServicesDiscovered 回调函数中,使用 BluetoothGatt 对象的 readCharacteristic 方法对特性进行读取。示例代码如下:
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        BluetoothGattService service = gatt.getService(UUID.fromString(service_uuid));
        if (service != null) {
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristic_uuid));
            if (characteristic != null) {
                gatt.readCharacteristic(characteristic);
            }
        }
    }
}

在读取操作完成后,蓝牙设备会调用 onCharacteristicRead 回调函数。可以在回调函数中获取到读取到的数据,示例代码如下:

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        byte[] data = characteristic.getValue();
        // 对读取到的数据进行处理
    }
}
  1. 写入数据
    在已连接蓝牙设备的 onServicesDiscovered 回调函数中,使用 BluetoothGatt 对象的 writeCharacteristic 方法对特性进行写入。示例代码如下:
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        BluetoothGattService service = gatt.getService(UUID.fromString(service_uuid));
        if (service != null) {
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristic_uuid));
            if (characteristic != null) {
                characteristic.setValue(data);
                gatt.writeCharacteristic(characteristic);
            }
        }
    }
}

在写入操作完成后,蓝牙设备会调用 onCharacteristicWrite 回调函数。可以在回调函数中判断写入结果是否成功,示例代码如下:

@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "Write characteristic success");
    } else {
        Log.d(TAG, "Write characteristic failed");
    }
}

根据引用中的代码,可以通过监听蓝牙断开连接状态来重新尝试连接蓝牙设备,具体步骤如下:

1.在需要监听蓝牙连接状态的地方创建一个 BroadcastReceiver,用于监控蓝牙断开连接状态:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            // 蓝牙连接断开,尝试重新连接
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            connectToDevice(device);
        }
    }
};

2.在启动蓝牙连接之前注册广播接收器:

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(mReceiver, filter);

3.启动蓝牙连接,如果连接失败,将会自动调用广播接收器的 onReceive 方法,尝试重新连接。

BluetoothDevice device = ... // 需要连接的蓝牙设备
connectToDevice(device);

注意事项:

  • 在重新连接之前,需要确保之前的蓝牙连接已经断开。
  • 如果设备蓝牙处于未启用状态,需要先启用蓝牙并且获取蓝牙权限才能进行连接。

Android 蓝牙连接过程中通常会经历以下几个步骤:

  1. 打开蓝牙并扫描周围的蓝牙设备。
  2. 与目标蓝牙设备建立连接。
  3. 在建立连接后进行服务发现,以检查目标蓝牙设备所支持的服务和特征。
  4. 根据所支持的服务和特征,开启相应的通道,以便进行数据传输。
  5. 进行数据传输。

其中,建立连接是连接过程中最重要的一步。在建立连接时,Android 设备会首先发送一个连接请求给目标蓝牙设备。一旦目标设备接受了连接请求,就会建立一个连接,并开始进行服务发现。在服务发现过程中,目标设备会发送一个包含其所支持的服务和特征的列表给 Android 设备。Android 设备会根据这个列表开启相应的通道,以便进行数据传输。

值得注意的是,在连接过程中有时候会出现配对的问题。如果配对失败,连接也会失败。在配对过程中,Android 设备会向目标设备发送一个配对请求,目标设备会弹出一个配对框,提示用户进行配对操作。如果用户在目标设备上点击了“确认”按钮,则配对成功,连接会继续进行。如果用户点击了“取消”按钮,则配对失败,连接也会中断。
在 Android 蓝牙连接过程中,出现连接失败的情况常见的原因有:蓝牙模块硬件故障、蓝牙模块与设备之间距离太远、蓝牙设备已经与其他设备绑定、蓝牙设备已经关闭等。以下是一些处理连接失败的方法:

1.重启蓝牙设备和手机
可以尝试重启蓝牙设备和手机,这样有时会解决连接问题。

2.确认蓝牙设备是否配对过
连接蓝牙设备前需要将蓝牙设备与手机配对,如果没有配对,连接也会失败。可以在蓝牙设备列表中查看已经配对的设备,并确认是否已经配对成功。

3.检查蓝牙设备是否处于可检测模式
在连接蓝牙设备前,需要将蓝牙设备设置为可被检测到的模式,否则手机无法搜索到蓝牙设备。

4.检查蓝牙设备是否已关闭
如果蓝牙设备已关闭,则手机无法搜索到设备,也就无法连接设备。需要确保蓝牙设备已经打开。

5.检查蓝牙设备是否支持当前的协议
蓝牙设备不一定支持所有的协议,如果蓝牙设备不支持当前的协议,连接也会失败。需要查看蓝牙设备的说明书,确认设备是否支持当前协议。

在Android蓝牙连接中,可以通过使用BluetoothAdapter类的方法来获取设备的名称和地址。
以下是获取设备名称和地址的示例代码:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
    String deviceName = device.getName();
    String deviceAddress = device.getAddress(); 
    // 可以在这里处理获取到的设备名称和地址
}

// 获取所有可用的蓝牙设备
bluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);

private final 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);
            String deviceName = device.getName();
            String deviceAddress = device.getAddress(); 
            // 可以在这里处理获取到的设备名称和地址
        }
    }
};

以上代码首先获取已配对的设备的名称和地址,并在获取到可用的蓝牙设备后注册了一个广播接收器来获取其他可用设备的名称和地址。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值