一步一步实现Android低功耗蓝牙(BLE)基本开发

项目需要接入两个低功耗蓝牙设备(BLE),并且与之交互(读/写)数据,所以看了下官方对于这块儿的介绍,总结了一下BLE开发中一些需要注意的地方以及基本流程。

BLE开发需要Android 4.3 (API level 18) 及以上

一.添加权限
为了能正常使用蓝牙相关功能(扫描等),首先需要添加以下权限:

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

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

在Android6.0及以上系统中,我们需要动态申请权限,这里推荐使用RxPermissions

简单介绍下RxPermissions如何引入。

1.在根build文件中添加代码:

...
allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
...

2.在对应moudle的build文件中添加依赖:

...
dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
}
...

3.使用:

RxPermissions rxPermissions=new RxPermissions(this);
rxPermissions.request(Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(granted -> {
                    if (granted) {
                        //权限允许成功
                    }
                });

如果想了解RxPermissions更多用法,戳这里

二.判断设备是否支持蓝牙
这里有两种处理方式:

  • 如果你想让只有支持BLE的手机才能安装你的应用程序的话,可以在清单文件中添加如下内容,这样的话如果设备不支持BLE的话你的应用都装不上,当然这种方式不太友好:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
  • 在代码中判断当前设备是否支持BLE,以对用户做出反馈。
    首先,在清单文件中声明需要使用BLE特性,不过required这里设置为false,然后在app运行时通过 PackageManager.hasSystemFeature()来判断设备是否支持ble:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

三.扫描蓝牙设备
BLE设备的扫描由BluetoothManager对象提供方法来实现,有两个扫描方法:


    public boolean startLeScan(BluetoothAdapter.LeScanCallback callback) {
        throw new RuntimeException("Stub!");
    }

    public boolean startLeScan(UUID[] serviceUuids, BluetoothAdapter.LeScanCallback callback) {
        throw new RuntimeException("Stub!");
    }

第二个方法允许我们提供特定的UUID,来扫描特定的设备,扫描结果通过BluetoothAdapter.LeScanCallback接口回调给我们:

 public interface LeScanCallback {
        /**
         * Callback reporting an LE device found during a device scan initiated
         * by the {@link BluetoothAdapter#startLeScan} function.
         *
         * @param device Identifies the remote device
         * @param rssi The RSSI value for the remote device as reported by the
         *             Bluetooth hardware. 0 if no RSSI value is available.
         * @param scanRecord The content of the advertisement record offered by
         *                   the remote device.
         */
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord);
    }

四.获取远程BLE设备
在扫描出设备以后,我们一般会选择某个扫描出来的设备,通过其地址获取一个远程的蓝牙设备对象。

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address)

五.连接BLE设备的GATT服务
与BLE设备交互的第一步是连接到它,更具体地说,连接到设备上的GATT服务。要在BLE设备上连接到GATT服务,可以使用connectGatt()方法。该方法接受三个参数:一个上下文对象、autoConnect(布尔值表示是否在BLE设备可用时自动连接到该设备),以及对BluetoothGattCallback的引用:

mBluetoothGatt = device.connectGatt(context, true, mGattCallback);

以上代码可以连接到由BLE设备托管的GATT服务,并返回一个BluetoothGatt实例,然后可以使用它来执行GATT客户端操作,例如写数据等。呼叫者(Android应用程序)是GATT客户端。连接状态,以及GATT的数据变化等通过BluetoothGattCallback接口回调给客户端(APP)。

一般使用BluetoothGattCallback的这些回调方法:

1.获取连接状态,在连接成功时扫描设备服务

@Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                if (connectChangedListener != null) {
                    connectChangedListener.onConnected();
                }
                mConnectionState = STATE_CONNECTED;
                mBluetoothGatt.discoverServices();

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                if (connectChangedListener != null) {
                    connectChangedListener.onDisconnected();
                }
                mConnectionState = STATE_DISCONNECTED;
            }
        }

2.获取服务,特性等
一个BLE设备可能有多个服务BluetoothGattService,同样每个服务可以有多个BluetoothGattCharacteristic特性。

@Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                List<BluetoothGattService> services = mBluetoothGatt.getServices();
                for (int i = 0; i < services.size(); i++) {
                    HashMap<String, BluetoothGattCharacteristic> charMap = new HashMap<>();
                    BluetoothGattService bluetoothGattService = services.get(i);
                    String serviceUuid = bluetoothGattService.getUuid().toString();
                    List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
                    for (int j = 0; j < characteristics.size(); j++) {
                        charMap.put(characteristics.get(j).getUuid().toString(), characteristics.get(j));
                    }
                    servicesMap.put(serviceUuid, charMap);
                }
                BluetoothGattCharacteristic bluetoothGattCharacteristic = getBluetoothGattCharacteristic(UUID_SERVICE, UUID_CHARACTERISTIC);
                if (bluetoothGattCharacteristic == null)
                    return;
                enableGattServicesNotification(bluetoothGattCharacteristic);
            } else {
                Log.w(TAG, " --------- onServicesDiscovered received: " + status);
            }
        }

在上面的代码中,我们将BLE设备的所有BluetoothGattServiceBluetoothGattCharacteristic全部保存下来,但是在实际需求中,我们一般只会与某个特定BluetoothGattService中的某个特性BluetoothGattCharacteristic进行数据读写。判断条件就是这里的UUID_SERVICEUUID_CHARACTERISTIC,这两个UUID一般提供BLE设备的时候会一并提供给我们。

找到这个特定的BluetoothGattCharacteristic后,我们希望它发生改变时可以得到通知,可以使用setCharacteristicNotification()方法为特性设置通知:

BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(UUID_DESCRIPTOR));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);

3.监听数据变化
经过以上设置,我们就可以在onCharacteristicChanged回调方法中获取BLE设备发过来的数据了:

@Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            //解析数据
            parseData(characteristic);
        }

当然,我们也可以用第五步中获取的mBluetoothGatt来向BLE设备发送数据:

mBleGattCharacteristic.setValue(HexUtil.hexStringToBytes(value));
boolean b=mBluetoothGatt.writeCharacteristic(mBleGattCharacteristic);

以上,就是Android端与BLE设备通信的基本开发流程,这里我抽成了一个Demo,项目目录如下:
这里写图片描述

几点说明:

  • 因为我这里需求是接入两个BLE设备,所以我抽取了一个BluetoothLeDeviceBase,代表基类设备,将一些通用的属性和操作封装在了这里
  • BluetoothLeDeviceA,BluetoothLeDeviceB代表具体的某个BLE设备,每个设备可能有不同之处,例如数据解析方式等。

完整代码地址:https://github.com/SolveBugs/BlogPracticeDems,目前只是基本的封装,后续会继续完善。

选择bluetoothbledemo这个moudle运行即可,界面如下:
这里写图片描述

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
BLE低功耗蓝牙)是一种通过蓝牙无线技术进行低功耗通信的协议。它是在传统蓝牙(Classic Bluetooth)的基础上发展而来,主要用于物联网、智能家居和健康追踪等领域。 BLE主要特点有以下几个方面: 1. 低功耗BLE采用了一种优化的通信方式,使设备在通信过程中的功耗大大降低,从而延长了设备的电池寿命,这对于需要长时间运行的设备非常重要。 2. 简化传输:BLE使用了一种称为GATT(通用属性)的协议,将数据分为服务和特征,通过读、写或订阅操作来传输数据,这种简化了传输过程,减少了额外的开销。 3. 快速连接:BLE的连接速度比传统蓝牙更快,可以在几十毫秒内建立连接,这对于移动设备和传感器等需要快速响应的设备非常重要。 4. 多设备连接:BLE支持同时连接多个设备,可以通过同一个移动设备与多个BLE设备进行通信,提高了系统的灵活性和可扩展性。 Android提供了一套完整的BLE开发API,开发者可以使用这些API来实现BLE通信功能。在Android中,开发BLE应用涉及到四个主要组件:BLE设备扫描、设备连接、数据传输和GATT服务管理。 开发者可以使用Android的BluetoothAdapter类来进行设备扫描和连接操作,可以通过BluetoothGatt类来进行GATT服务的操作,包括读、写、订阅等。 总之,BLE作为一种低功耗蓝牙通信协议,在物联网和智能设备领域应用广泛。在Android平台上进行BLE开发,可以借助Android提供的API,快速实现BLE通信功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值