安卓读取蓝牙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的UUIDpublic static final UUID DEVICE_INFO_SERVICE_UUID = UUID.fromString("0000180A-0000-1000-8000-00805f9b34fb");//characteristic的UUIDpublic 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");private final static UUID[] characteristicUUIDList = {MANUFACTURER_Name_UUID,SN_UUID,MODEL_NAME_UUID,SOFTWARE_VERSION_UUID,FIRMWARE_VERSION_UUID};private int index = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);while(true) {if(alreadyConnected == false) {findGattDevice();}try {Thread.sleep(60000);} catch (InterruptedException e) {e.printStackTrace();}}}//GATT连接回调接口BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {super.onConnectionStateChange(gatt, status, newState);if (newState == BluetoothProfile.STATE_CONNECTED) {//GATT连接成功Log.i(TAG, "GATT connect success");alreadyConnected = true;if(gatt != null) {gatt.discoverServices();}} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//GATT连接断开Log.i(TAG, "GATT disconnect");closeGatt();}}@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {super.onServicesDiscovered(gatt, status);Log.i(TAG, "onServicesDiscovered status:" + status);if (status == BluetoothGatt.GATT_SUCCESS) {//根据uuid获取指定的servicemGattService = gatt.getService(DEVICE_INFO_SERVICE_UUID);if (mGattService == null) {Log.i(TAG, "service is null, disconnect GATT");closeGatt();return;} else {Log.i(TAG, "find service!");}//根据uuid获取指定的characteristicmGattCharacteristic = mGattService.getCharacteristic(characteristicUUIDList[0]);if (mGattCharacteristic == null) {Log.i(TAG, "characteristic is null");closeGatt();return;} else {//读取蓝牙特征值Log.i(TAG, "start read characteristic");mBluetoothGatt.readCharacteristic(mGattCharacteristic);}} else {Log.i(TAG, "onServicesDiscovered status false");closeGatt();}}@Overridepublic void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {super.onCharacteristicRead(gatt, characteristic, status);if (status == BluetoothGatt.GATT_SUCCESS) {String value = new String(characteristic.getValue()).trim().replace(" ", "");Log.i(TAG, "read data:" + value);if(mGattService == null) {Log.i(TAG, "service is null, disconnect GATT");closeGatt();return;}index ++;if(index < characteristicUUIDList.length) {mGattCharacteristic = mGattService.getCharacteristic(characteristicUUIDList[index]);} else {closeGatt();return;}if (mGattCharacteristic == null) {Log.i(TAG, "characteristic is null");closeGatt();return;} else {//读取蓝牙特征值Log.i(TAG, "start read characteristic");mBluetoothGatt.readCharacteristic(mGattCharacteristic);}} else {Log.i(TAG, "onCharacteristicRead status false");closeGatt();}}@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {super.onCharacteristicWrite(gatt, characteristic, status);Log.i(TAG, "onCharacteristicWrite:" + characteristic.getUuid().toString());}};//查找是否有已连接的BLE设备private void findGattDevice() {Log.i(TAG, "findGattDevice start");BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);List<BluetoothDevice> connectedList = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);if(connectedList == null) {Log.i(TAG, "connectedList is null");return;}int i = 0;Log.i(TAG, "connectedList size:" + connectedList.size());while(connectedList.size() > i) {BluetoothDevice bluetoothDevice = connectedList.get(i);if(bluetoothDevice != null) {Log.i(TAG, "find device:" + bluetoothDevice.getName());try {//建立GATT连接mBluetoothGatt = bluetoothDevice.connectGatt(this, false, mGattCallback);} catch (Exception e) {Log.i(TAG, "findGattDevice e:" + e.getMessage());}}i++;}}//关闭GATT连接private void closeGatt() {Log.i(TAG, "closeGatt start");alreadyConnected = false;mGattService = null;mGattCharacteristic = null;index = 0;if(mBluetoothGatt != null) {Log.i(TAG, "closeGatt do close");try {mBluetoothGatt.disconnect();mBluetoothGatt.close();} catch (Exception e) {Log.i(TAG, "closeGatt e:" + e.getMessage());}mBluetoothGatt = null;}}
}

在AndroidManifest.xml中声明需要用到的权限:

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

监听广播方式代码实现

todo

安卓读取蓝牙BLE设备信息相关推荐

  1. 蓝牙BLE设备主机重启回连流程分析

    本文出自:<蓝牙BLE设备主机重启回连流程分析> 如果一个BLE设备已经与蓝牙中心设备连接上,那么当中心设备的断电重启,其依然会和配对过的BLE设备连接上,而不需要重新走配对的流程,这个过 ...

  2. Windows,Android设备刷机(重装系统)时遇到USB读取不到设备信息(设备驱动异常)问题及解决办法

    Windows,Android设备刷机(重装系统)时遇到USB读取不到设备信息(设备驱动异常)问题及解决办法 前言 当刷Android系统时,我们要进入boot模式,**adb reboot boot ...

  3. android 安卓APP获取手机设备信息和手机号码的代码示例

    下面我从安卓开发的角度,简单写一下如何获取手机设备信息和手机号码 准备条件:一部安卓手机.手机SIM卡确保插入手机里.eclipse ADT和android-sdk开发环境 第一步:新建一个andro ...

  4. android app 手机号码,android 安卓APP获取手机设备信息和手机号码的代码示例 .

    下面我从安卓开发的角度,简单写一下如何获取手机设备信息和手机号码 准备条件:一部安卓手机.手机SIM卡确保插入手机里.eclipse ADT和android-sdk开发环境 第一步:新建一个andro ...

  5. android app 手机号码,android 安卓APP获取手机设备信息和手机号码的代码示例

    下面我从安卓开发的角度,简单写一下如何获取手机设备信息和手机号码 准备条件:一部安卓手机.手机SIM卡确保插入手机里.eclipse ADT和android-sdk开发环境 第一步:新建一个andro ...

  6. 蓝牙BLE设备连接与通信

    1.在建立BLE设备进行通信时注意3点 1.1.蓝牙位置权限必须动态申请(Android 6.0以上),如果没有动态申请会出现下面的问题 Need BLUETOOTH permission: Neit ...

  7. Android6.0以上系统搜索不到 蓝牙BLE 设备问题

    最近开发一款软件,一开始一切顺利,但是在连接外围BLE 设备时,发现需要Location的权限, <uses-permission android:name="android.perm ...

  8. Win10 平台C#与低功耗蓝牙BLE设备通信案例

    前几天接了个单,客户要在win10电脑上做个工具软件,跟蓝牙锁设备相互通信.一开始以为是普通的蓝牙设备呢,收到客户寄来的测试设备,才发现是低功耗BLE蓝牙设备. PS:当时我研发用的台式机是没有蓝牙设 ...

  9. java实现获取手机设备号_Java 安卓获得获得手机设备信息

    1)android 获取设备型号.OS版本号: import android.os.Build; // ..... Build bd = new Build(); String model = bd. ...

最新文章

  1. Netty - I/O模型之NIO
  2. mysql命令参数详解_详解Mysql命令大全(推荐)
  3. 全球及中国家用空气净化器市场销售需求及营销策略模式分析报告2022-2027年
  4. Activiti 7.1.4 发布,业务流程管理与工作流系统
  5. 操作系统例题:某文件系统中,针对每个文件,用户类别分为4类:安全管理员、文件主、文件主的伙伴、其他用户;访问权限分为5种:完全控制、执行、修改、读取、写入。若文件控制块中用二进制位串表示文件权限,为表
  6. 金华职业技术学院计算机应用技术分数线,金华职业技术学院录取分数线2021是多少分(附历年录取分数线)...
  7. 【C】揭秘rand()函数;
  8. 持续集成部署Jenkins工作笔记0009---创建SVN版本库并提交Maven工程
  9. 使用Python中的mock模块进行单元测试
  10. 使用锚标记返回网页顶部的方法
  11. C++ printf输出
  12. stm32f412新工程配置的记录
  13. android全局屏幕自动旋转,Android屏幕旋转
  14. TrueCrypt 使用经验[1]:关于加密算法和加密盘的类型
  15. 智能家居控制系统制作技术_智能家居控制系统是什么_智能家居控制系统的由来-装修攻略...
  16. win10如何查看服务器日志文件,系统日志在哪里?win10系统错误日志怎么查看
  17. ROS2系列知识【5】:从海龟教程开始【1】
  18. 个人介绍 php 怎么说,个人介绍怎么写
  19. 威联通[vNAS內置虚拟机]体验评测 让企业实现无限可能
  20. 剑指offer----C语言版----第十一天

热门文章

  1. 3. Web 服务原理
  2. 矩阵论——各种矩阵的关系
  3. 世界上并无汉语编程——正如世界上并无英语编程
  4. “定量宽松”货币政策出炉,黄金走向何方?
  5. 肖 sir_就业课__009ui自动化讲解
  6. 利用人性弱点的互联网产品(一)贪婪
  7. Express+MySQL实现图片上传到服务器并把路径保存到数据库中
  8. Get Offer 之遇到了阿里女神怎么选?
  9. vector 数组的用法
  10. sci hub论文下载方法及脚本插件安装