当前位置: 首页 > news >正文

android 获取手机配对的蓝牙耳机的电量

第一步 首先添加权限,记得动态申请

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

第二步,获取配对的设备

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {textView.setText("不支持蓝牙");// 设备不支持蓝牙Log.e(TAG, "Device doesn't support Bluetooth");
} else {if (!bluetoothAdapter.isEnabled()) {Log.e(TAG, "open Bluetooth");// 请求用户打开蓝牙Intent enableBtIntent = new         Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableBtIntent, 99);} else {textView.setText("蓝牙已打开");getData();}
}
private void getData() {Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();if (pairedDevices.size() > 0) {for (BluetoothDevice device : pairedDevices) {if (device.getName().contains("HUAWEI")) { //目标设备// 假设我们找到了目标蓝牙耳机getBatteryInfo(device);}}} else {tvContent.setText("no pair devices");}
}

第三步,根据device获取电量,这里有两种方式

方式1,直接反射系统接口获取,但是获取的电量不是精确的,是两个耳机中电量最低的那个整数值,而且并不是实时的,每变化10%更新一次

private void getBatteryInfo(BluetoothDevice device) {try {Method getBatteryLevel = device.getClass().getMethod("getBatteryLevel");int batteryLevel = (Integer) getBatteryLevel.invoke(device);Log.e(TAG, "Battery Level: " + batteryLevel + "%");showBatteryLevelToUser(batteryLevel);} catch (Exception e) {e.printStackTrace();Log.e(TAG, "Failed to get battery level");}
}

方式2,适用于支持ble蓝牙的设备,通过BluetoothGatt类去获取,这种方式需要知道电量uuid,虽然官方有默认的电量uuid,但是部分厂家会用自己定义的,电量特征的uuid如果是左右两个耳机,可能是不同的,需要分别获取电量值。

  • 真无线耳机(TWS)通常将左右耳设计为两个独立的BLE设备,或通过单一设备的不同特征值(Characteristic)区分左右电量。
  • 标准做法:左/右耳机电量分别存储在Battery Service下的不同特征值中(例如左耳UUID: 00002a19-0000-1000-8000-00805f9b34fb,右耳可能为自定义UUID)
private static final UUID MY_SERVICE_UUID = UUID.fromString("0000180F-0000-1000-8000-00805F9B34FB"); // 电池服务UUID
private static final UUID MY_CHARACTERISTIC_UUID = UUID.fromString("00002A19-0000-1000-8000-00805F9B34FB"); // 电池电量级别特性UUID
private void connectToDevice(BluetoothDevice device) {@SuppressLint("MissingPermission")BluetoothGatt bluetoothGatt = device.connectGatt(this, false, new         BluetoothGattCallback() {@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int         newState) {if (newState == BluetoothProfile.STATE_CONNECTED) { // 成功连接gatt.discoverServices(); // 成功连接} else if (newState == BluetoothProfile.STATE_DISCONNECTED){Log.e(TAG,"gatt disConnect");} else {Log.e(TAG,"gatt fail");}}@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {List<BluetoothGattService> services = gatt.getServices();Log.e(TAG,"BluetoothGattService size" + services.size());BluetoothGattService batteryService = gatt.getService(MY_SERVICE_UUID); // 确认是电池服务if (batteryService != null) {BluetoothGattCharacteristic batteryLevelCharacteristic = batteryService.getCharacteristic(MY_CHARACTERISTIC_UUID); // 确认是电量特征,左右耳机可能不一样,需要分别获取,这里只获取一个boolean success = gatt.readCharacteristic(batteryLevelCharacteristic); // 读取电量信息if (success) {Log.e(TAG,"gatt getBattery success");// 等待 onCharacteristicRead回调来获取数据} else {// 读取失败处理Log.e(TAG,"gatt getBattery fail");}} else {Log.e(TAG, "batteryService is null");}} else {// 服务发现失败处理Log.e(TAG,"onServicesDiscovered fail");}}@Overridepublic void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {int batteryLevel = characteristic.getValue()[0];// 直接转换为整数Log.e(TAG, "Battery Level: " + batteryLevel + "%");if (characteristic.getUuid().equals(“左边耳机的uuid”)) { Log.d(TAG, "左耳电量: " + batteryLevel + "%"); } else if (characteristic.getUuid().equals(“右边耳机的uuid”)) {                     Log.d(TAG, "右耳电量: " + batteryLevel + "%"); }// 将电量信息展示给用户showBatteryLevelToUser(batteryLevel);}}});
}
http://www.lryc.cn/news/581584.html

相关文章:

  • 【PyTorch】PyTorch中torch.nn模块的池化层
  • 全能视频处理工具介绍说明
  • [shad-PS4] docs | 内核/系统服务 | HLE-高等级模拟
  • Spark流水线数据质量检查组件
  • UNet改进(16):稀疏注意力(Sparse Attention)在UNet中的应用与优化策略
  • Redis集群和 zookeeper 实现分布式锁的优势和劣势
  • 物联网实施与运维【路由器/网关配置】+智能楼道系统
  • python库 dateutil 库的各种案例的使用详解
  • 【Note】《Kafka: The Definitive Guide》第三章: Kafka 生产者深入解析:如何高效写入 Kafka 消息队列
  • Android studio在点击运行按钮时执行过程中输出的compileDebugKotlin 这个任务是由gradle执行的吗
  • 升级AGP(Android Gradle plugin)和gradle的版本可以提高kapt的执行速度吗
  • 【python】对纯二进制向量(仅包含 0 和 1,长度为 8 或 16)的检测和提取
  • 基于腾讯云开发与“人·事·财·物”架构理念的家政预约小程序设计与实现
  • 【Python练习】030. 编写一个函数,实现字符串的反转
  • Python 中 ffmpeg-python 库的详细使用
  • 一条 SQL 语句的内部执行流程详解(MySQL为例)
  • 2025 JuniorCryptCTF re 部分wp
  • 重力翻转者:原创趣味小游戏
  • 前端开发常见问题(从布局到性能优化)
  • 【libm】 10 rem_pio2函数 (rem_pio2.rs)
  • 人工智能之数学基础:线性回归算法的矩阵参数求导
  • 传统微商困境与开源链动2+1模式、AI智能名片及S2B2C商城小程序的转型破局
  • AUTOSAR进阶图解==>AUTOSAR_SWS_V2XFacilities
  • Hadoop MapReduce 入门
  • Hadoop高可用集群搭建
  • k8s-服务发布基础
  • 小菜狗的云计算之旅,学习了解rsync+sersync实现数据实时同步(详细操作步骤)
  • 【Linux网络编程】Socket - UDP
  • 儿童趣味记忆配对游戏
  • 【CSS-15】深入理解CSS transition-duration:掌握过渡动画的时长控制