当前位置: 首页 > 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.xdnf.cn/news/1084069.html

相关文章:

  • python中生成假数据的库 faker 的详细使用,包括详细案例(生成逼真假数据)
  • Go语言实现双Token登录的思路与实现
  • 人工智能之数学基础:线性回归算法的矩阵参数求导
  • QueryWrapper 类的作用与示例详解
  • QT并发机制
  • 数学建模的一般步骤
  • 暑假复习篇之五子棋③【人机对战篇1】
  • Oracle使用SQL一次性向表中插入多行数据
  • 数据可视化中常用的图表类型 及其适用场景,涵盖基础到高级,帮助你根据数据类型和展示目标选择合适的图表:
  • 【论文笔记】【强化微调】Pixel Reasoner:早期 tool call 的调用
  • react当中的this指向
  • 【从0-1的CSS】第3篇:盒子模型与弹性布局
  • 《前端路由重构:解锁多语言交互的底层逻辑》
  • 3. lvgl 9.3 vscode 模拟环境搭建 lv_port_pc_vscode-release-v9.3
  • Paimon索引概述
  • vue3.4中的v-model的用法~
  • 支持向量机(SVM)在肝脏CT/MRI图像分类(肝癌检测)中的应用及实现
  • 从源码到思想:OneCode框架模块化设计如何解决前端大型应用痛点
  • Application的onLowMemory从Android API 34开始系统不再触发,从API 35开始废弃
  • 【BTC】协议(共识机制)
  • 自定义指令
  • java+vue+SpringBoo职业生涯规划系统(程序+数据库+报告+部署教程+答辩指导)
  • 【AI大模型】Spring AI 基于mysql实现对话持久存储详解
  • 多模态大语言模型arxiv论文略读(149)
  • 【网络协议安全】任务13:ACL访问控制列表
  • 深度学习图像分类数据集—蘑菇可食性识别分类
  • 使用Python将PDF转换成word、PPT
  • 量子计算机技术(第二节,到底什么是量子)
  • 【CSS-15】深入理解CSS transition-duration:掌握过渡动画的时长控制
  • 高速信号眼图