Android BLE蓝牙App:连接与发现服务

北极星光 2024-06-10 ⋅ 34 阅读

在Android开发中,使用蓝牙技术进行设备间通信是非常常见的需求。在近几年,BLE(Bluetooth Low Energy)蓝牙技术越来越被广泛应用于各种设备,例如智能手环、智能灯泡等。本博客将介绍如何在Android应用中使用BLE技术进行蓝牙设备的连接与服务发现。

连接蓝牙设备

要连接到蓝牙设备,首先需要获取设备的蓝牙适配器实例,并确保蓝牙功能已经开启:

// 获取蓝牙适配器
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// 检查蓝牙功能是否可用
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
    // 蓝牙不可用,进行处理
    ...
} else {
    // 蓝牙可用,进行设备搜索
    ...
}

在确保蓝牙可用后,我们可以开始搜索附近的蓝牙设备:

// 开始设备搜索
bluetoothAdapter.startDiscovery();

搜索到设备时,我们可以注册一个广播接收器来接收设备的相关信息:

// 创建广播接收器
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // 获取搜索到的设备
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            
            // 处理设备信息
            ...
        }
    }
};

// 注册广播接收器
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);

发现服务

连接到蓝牙设备后,接下来可以开始发现设备提供的服务。首先需要获取设备的BluetoothGatt实例,然后通过该实例进行服务发现:

// 连接到蓝牙设备
device.connectGatt(context, false, gattCallback);

在连接成功后,可以实现BluetoothGattCallback来处理服务发现的回调:

private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // 设备连接成功,开始服务发现
            gatt.discoverServices();
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            // 服务发现成功,获取设备的服务列表
            List<BluetoothGattService> services = gatt.getServices();
            
            // 处理服务列表
            ...
        }
    }
};

通过以上的代码,我们可以获取到连接设备所提供的所有服务,并对其进行相应的操作。

本博客简要介绍了Android BLE蓝牙App中连接与发现服务的实现方法。掌握这些基础知识后,你可以根据自己的需求进一步开发更复杂的蓝牙功能,例如数据传输、服务控制等。希望这篇博客对你在Android BLE开发中有所帮助!

参考文献:

  1. Android Developer Documentation
  2. Android BLE Guide

全部评论: 0

    我有话说: