Android-低功耗蓝牙BLE(Bluetooth Low Energy)开发

2024-05-13 01:32

本文主要是介绍Android-低功耗蓝牙BLE(Bluetooth Low Energy)开发,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.前言

1、Android 4.3 (API Level 18)才开始提供低功耗蓝牙开发API;
2、根据API可以 发现设备、查询服务、读写characteristics;
3、顾名思义,BLE出现旨在显著地降低能耗,这就使得app可以和一些低功耗设备交互,例如:接近传感器、心率监视器,健身设备,等等。

2.关键术语和概念

  1. Generic Attribute Profile (GATT):GATT协议定义了一个通用的规范,这个规范用于在BLE 连接上发送和接收一些短消息;
  2. Attribute Protocol (ATT):GATT 建立在ATT上面,ATT是一种最优化的协议对于BLE设备;
  3. Characteristic:这个东西可以被看成一个类来描述一些交互的信息;
  4. Descriptor:描述符,定义一些属性来描述Characteristic的值;
  5. Service:用来搜集Characteristic的服务,例如:心率监测器搜集一些心率测量相关的Characteristic数据;

3.manifest 权限配置
声明权限

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

静态声明以下语句表示app是否支持BLE,required=”true”表支持,反之则不支持;

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

之后在代码检查设备是否支持BLE

// 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)) { //不支持 todo...
}else{ //支持 todo...
}

4. 配置BLE

  1. 前提是设备支持BLE;
  2. 如果可能出现为false的情况下,我们有必要在代码中动态检查是否支持BLE;
//初始化蓝牙适配器,核心类
final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
private BluetoothAdapter mBluetoothAdapter;
...
//如果蓝牙适配器==null 或者 蓝牙没有打开,代码请求打开蓝牙
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

5.搜索设备

  1. 因为扫描设备比较耗电,所以一旦你发现了想要的设备,立即停止扫描;
  2. 千万不要不停地循环扫描,而是设置扫描的时间,因为之前可用的设备可能离开BLE的范围,这时候还在循环扫描比较浪费电;
  3. 注意:我们不能同时扫描 低功耗蓝牙设备(BLE)传统蓝牙设备
//startScan有很多个重载的方法 
mBluetoothAdapter.startScan(BluetoothAdapter.LeScanCallback);mBluetoothAdapter.startScan (List<ScanFilter> filters, ScanSettings settings, ScanCallback callback);...
/*** Activity 示例:扫描和展示可用BLE设备*/
public class DeviceScanActivity extends ListActivity {private BluetoothAdapter mBluetoothAdapter;private boolean mScanning;private Handler mHandler;// 扫描时间 10秒private static final long SCAN_PERIOD = 10000;...private void scanLeDevice(final boolean enable) {if (enable) {// 通过Handler延迟任务,取消扫描mHandler.postDelayed(new Runnable() {@Overridepublic void run() {mScanning = false;mBluetoothAdapter.stopLeScan(mLeScanCallback);}}, SCAN_PERIOD);mScanning = true;//开始扫描mBluetoothAdapter.startLeScan(mLeScanCallback);//扫描指定UUID的设备使用面这个方法startLeScan(UUID[], BluetoothAdapter.LeScanCallback)} else {mScanning = false;//停止扫描mBluetoothAdapter.stopLeScan(mLeScanCallback);}...}
...
}
//BluetoothAdapter.LeScanCallback实现
private LeDeviceListAdapter mLeDeviceListAdapter;
...
// 扫描设备后回调接口
private BluetoothAdapter.LeScanCallback mLeScanCallback =new BluetoothAdapter.LeScanCallback() {@Overridepublic void onLeScan(final BluetoothDevice device, int rssi,byte[] scanRecord) {//device 扫描到的设备}
};

6. 连接到服务(GATT Server)

//参数一 Context
//参数二 Boolean 是否尝试自动连接当BLE设备变得可用的时候
//参数三 BluetoothGattCallbac 回调接口
mBluetoothGatt = device.connectGatt(Context, Boolean, BluetoothGattCallback);
// A service that interacts with the BLE device via the Android BLE API.
//开启服务,通过Android BLE API 实现和BLE设备的交互
public class BluetoothLeService extends Service {private final static String TAG = BluetoothLeService.class.getSimpleName();private BluetoothManager mBluetoothManager;private BluetoothAdapter mBluetoothAdapter;private String mBluetoothDeviceAddress;private BluetoothGatt mBluetoothGatt;private int mConnectionState = STATE_DISCONNECTED;private static final int STATE_DISCONNECTED = 0;private static final int STATE_CONNECTING = 1;private static final int STATE_CONNECTED = 2;public final static String ACTION_GATT_CONNECTED ="com.example.bluetooth.le.ACTION_GATT_CONNECTED";public final static String ACTION_GATT_DISCONNECTED ="com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";public final static String ACTION_GATT_SERVICES_DISCOVERED ="com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";public final static String ACTION_DATA_AVAILABLE ="com.example.bluetooth.le.ACTION_DATA_AVAILABLE";public final static String EXTRA_DATA ="com.example.bluetooth.le.EXTRA_DATA";public final static UUID UUID_HEART_RATE_MEASUREMENT =UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);// Various callback methods defined by the BLE API.//BLE API 定义了多种回调方法private final BluetoothGattCallback mGattCallback =new BluetoothGattCallback() {@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {String intentAction;if (newState == BluetoothProfile.STATE_CONNECTED) { //连上GATT服务intentAction = ACTION_GATT_CONNECTED;mConnectionState = STATE_CONNECTED;broadcastUpdate(intentAction);Log.i(TAG, "Connected to GATT server.");Log.i(TAG, "Attempting to start service discovery:" +mBluetoothGatt.discoverServices());} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//断开服务连接intentAction = ACTION_GATT_DISCONNECTED;mConnectionState = STATE_DISCONNECTED;Log.i(TAG, "Disconnected from GATT server.");broadcastUpdate(intentAction);}}@Override// New services discovered//新的服务被发现public void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);} else {Log.w(TAG, "onServicesDiscovered received: " + status);}}@Override// Result of a characteristic read operation//public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);}}...};
...
}
private void broadcastUpdate(final String action) {final Intent intent = new Intent(action);sendBroadcast(intent);
}private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic) {final Intent intent = new Intent(action);// This is special handling for the Heart Rate Measurement profile. Data// parsing is carried out as per profile specifications.if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {int flag = characteristic.getProperties();int format = -1;if ((flag & 0x01) != 0) {format = BluetoothGattCharacteristic.FORMAT_UINT16;Log.d(TAG, "Heart rate format UINT16.");} else {format = BluetoothGattCharacteristic.FORMAT_UINT8;Log.d(TAG, "Heart rate format UINT8.");}final int heartRate = characteristic.getIntValue(format, 1);Log.d(TAG, String.format("Received heart rate: %d", heartRate));intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));} else {// For all other profiles, writes the data formatted in HEX.final byte[] data = characteristic.getValue();if (data != null && data.length > 0) {final StringBuilder stringBuilder = new StringBuilder(data.length);for(byte byteChar : data)stringBuilder.append(String.format("%02X ", byteChar));intent.putExtra(EXTRA_DATA, new String(data) + "\n" +stringBuilder.toString());}}sendBroadcast(intent);
}

通过广播接收者处理这些事件

// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a
// result of read or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {final String action = intent.getAction();if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {mConnected = true;updateConnectionState(R.string.connected);invalidateOptionsMenu();} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {mConnected = false;updateConnectionState(R.string.disconnected);invalidateOptionsMenu();clearUI();} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {// Show all the supported services and characteristics on the// user interface.displayGattServices(mBluetoothLeService.getSupportedGattServices());} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));}}
};

7.连上服务后,可以读取数据了

public class DeviceControlActivity extends Activity {...// Demonstrates how to iterate through the supported GATT// Services/Characteristics.// In this sample, we populate the data structure that is bound to the// ExpandableListView on the UI.private void displayGattServices(List<BluetoothGattService> gattServices) {if (gattServices == null) return;String uuid = null;String unknownServiceString = getResources().getString(R.string.unknown_service);String unknownCharaString = getResources().getString(R.string.unknown_characteristic);ArrayList<HashMap<String, String>> gattServiceData =new ArrayList<HashMap<String, String>>();ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData= new ArrayList<ArrayList<HashMap<String, String>>>();mGattCharacteristics =new ArrayList<ArrayList<BluetoothGattCharacteristic>>();// Loops through available GATT Services.for (BluetoothGattService gattService : gattServices) {HashMap<String, String> currentServiceData =new HashMap<String, String>();uuid = gattService.getUuid().toString();currentServiceData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));currentServiceData.put(LIST_UUID, uuid);gattServiceData.add(currentServiceData);ArrayList<HashMap<String, String>> gattCharacteristicGroupData =new ArrayList<HashMap<String, String>>();List<BluetoothGattCharacteristic> gattCharacteristics =gattService.getCharacteristics();ArrayList<BluetoothGattCharacteristic> charas =new ArrayList<BluetoothGattCharacteristic>();// Loops through available Characteristics.for (BluetoothGattCharacteristic gattCharacteristic :gattCharacteristics) {charas.add(gattCharacteristic);HashMap<String, String> currentCharaData =new HashMap<String, String>();uuid = gattCharacteristic.getUuid().toString();currentCharaData.put(LIST_NAME, SampleGattAttributes.lookup(uuid,unknownCharaString));currentCharaData.put(LIST_UUID, uuid);gattCharacteristicGroupData.add(currentCharaData);}mGattCharacteristics.add(charas);gattCharacteristicData.add(gattCharacteristicGroupData);}...}
...
}

8.接收GATT通知

private BluetoothGatt mBluetoothGatt;
BluetoothGattCharacteristic characteristic;
boolean enabled;
...
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
...
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);

onCharacteristicChanged() 回调用来监听远程设备characteristic changes

@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

8.App和BLE设备交互完成,需要释放资源

public void close() {if (mBluetoothGatt == null) {return;}mBluetoothGatt.close();mBluetoothGatt = null;
}

这篇关于Android-低功耗蓝牙BLE(Bluetooth Low Energy)开发的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/984310

相关文章

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

Linux_kernel驱动开发11

一、改回nfs方式挂载根文件系统         在产品将要上线之前,需要制作不同类型格式的根文件系统         在产品研发阶段,我们还是需要使用nfs的方式挂载根文件系统         优点:可以直接在上位机中修改文件系统内容,延长EMMC的寿命         【1】重启上位机nfs服务         sudo service nfs-kernel-server resta

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。

Vue3项目开发——新闻发布管理系统(六)

文章目录 八、首页设计开发1、页面设计2、登录访问拦截实现3、用户基本信息显示①封装用户基本信息获取接口②用户基本信息存储③用户基本信息调用④用户基本信息动态渲染 4、退出功能实现①注册点击事件②添加退出功能③数据清理 5、代码下载 八、首页设计开发 登录成功后,系统就进入了首页。接下来,也就进行首页的开发了。 1、页面设计 系统页面主要分为三部分,左侧为系统的菜单栏,右侧