当前位置: 首页 > 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.dtcms.com/a/268429.html

相关文章:

  • Flutter 项目开启 UI 层级虚线(UI Guides)
  • 【C++】string类(二)相关接口介绍及其使用
  • 植物大战僵尸杂交重制版1.0,经典焕新,重燃策略塔防之火
  • Altium Designer使用入门(非精通)教程 第三章(PCB绘制)
  • 前端开发深度剖析:核心痛点、隐藏陷阱与系统解决方案
  • 【MySQL进阶】MySQL架构
  • 【HarmonyOS】鸿蒙应用开发Text控件常见错误
  • AI+Web3:从自动化工具到自主经济体的范式革命
  • 爬虫-协议基础
  • 1865.找出和为指定值得下标对
  • Java笔记-下
  • MyBatis-Plus分页拦截器原理深度解析
  • new与malloc[c++面试系列]
  • GCC/G++编译器详解:从编译原理到动静态链接
  • 2025 JuniorCryptCTF re 部分wp
  • 【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
  • 【Docker基础】Docker数据卷管理:docker volume rm与prune命令对比
  • 计算机网络实验——配置ACL
  • vue3 当前页面方法暴露
  • 「Java题库」基础程序设计(理论+操作)
  • Excel 日期计算与最小日期选择(附示例下载)
  • DAY 49
  • monorepo + Turborepo --- 开发应用程序
  • Go语言实现双Token登录的思路与实现
  • 微服务基础:Spring Cloud Alibaba 组件有哪些?
  • 随机森林算法详解:Bagging思想的代表算法
  • 自存bro code java course 笔记(2025 及 2020)
  • 【Linux网络编程】Socket - UDP
  • CppCon 2018 学习:What do you mean “thread-safe“
  • Linux操作系统之文件(五):文件系统(下)