安卓读取蓝牙BLE设备信息
简介
目前,许多项目都会涉及与BLE设备进行交互的功能,接下来说一下读取BLE设备信息的具体实现流程。安卓BLE相关接口介绍详见官网链接:
https://developer.android.google.cn/guide/topics/connectivity/bluetooth-le
轮询方式代码实现
这里实现的示例代码,每60秒通过bluetoothManager查询当前是否有已连接的BLE设备,如果有,则与该设备建立GATT连接,读取设备信息,读完之后断开GATT连接。
package com.komect.gatttest2;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private String TAG = "BLE";
private BluetoothGatt mBluetoothGatt;
private BluetoothGattCharacteristic mGattCharacteristic;
private BluetoothGattService mGattService;
private boolean alreadyConnected = false;
//service的UUID
public static final UUID DEVICE_INFO_SERVICE_UUID = UUID.fromString("0000180A-0000-1000-8000-00805f9b34fb");
//characteristic的UUID
public static final UUID MANUFACTURER_Name_UUID = UUID.fromString("00002A29-0000-1000-8000-00805f9b34fb");
public static final UUID SN_UUID = UUID.fromString("00002A25-0000-1000-8000-00805f9b34fb");
public static final UUID MODEL_NAME_UUID = UUID.fromString("00002A24-0000-1000-8000-00805f9b34fb");
public static final UUID SOFTWARE_VERSION_UUID = UUID.fromString("00002A27-0000-1000-8000-00805f9b34fb");
public static final UUID FIRMWARE_VERSION_UUID = UUID.fromString("00002A26-0000-1000-8000-00805f9b34fb");
public static final UUID MAC_UUID = UUID.fromString("00002A23-0000-1000-8000-00805f9b34fb"