androidQ(10.0) 读取蓝牙设备当前电量并显示

简介: androidQ(10.0) 读取蓝牙设备当前电量并显示

效果图


华为手机顶部状态栏


UCMBHf.png

我们客制化后最终效果


UCMJ4e.png


实现步骤


1、获取蓝牙设备连接成功后的电量值

2、跟踪蓝牙图标显示流程

3、制作蓝牙带电量图标

4、获取电量后显示对应电量值图标


文件修改清单

 vendor/mediatek/proprietary/packages/apps/SystemUI/res/drawable/ic_bluetooth_connected_super.xml                   
 vendor/mediatek/proprietary/packages/apps/SystemUI/res/drawable/stat_sys_data_bluetooth_connected_battery_0.xml  
 vendor/mediatek/proprietary/packages/apps/SystemUI/res/drawable/stat_sys_data_bluetooth_connected_battery_1.xml   
 vendor/mediatek/proprietary/packages/apps/SystemUI/res/drawable/stat_sys_data_bluetooth_connected_battery_2.xml   
 vendor/mediatek/proprietary/packages/apps/SystemUI/res/drawable/stat_sys_data_bluetooth_connected_battery_3.xml  
 vendor/mediatek/proprietary/packages/apps/SystemUI/res/drawable/stat_sys_data_bluetooth_connected_battery_4.xml   
 vendor/mediatek/proprietary/packages/apps/SystemUI/res/drawable/stat_sys_data_bluetooth_connected_battery_5.xml   
 vendor/mediatek/proprietary/packages/apps/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java     


除了 PhoneStatusBarPolicy.java 之外其余都是新增蓝牙图标相关资源文件,资源文件不再贴出,可以去这里下载


资源文件选用 xml path 绘制,好处就是能跟随系统状态栏切换背景色,如果采用 png 图片将需要处理监听状态栏底色改变


读取已连接蓝牙设备电量值,在网上搜索后找到了一个工具类,简单试了下发现可用,通过反射调用 BluetoothDevice 的


getBatteryLevel 方法获取电量值

private  int getBluetoothDeviceBattery(){
        int battery = -1;
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;
        try {
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            method.setAccessible(true);
            int state = (int) method.invoke(btAdapter, (Object[]) null);
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                for (BluetoothDevice device : devices) {
                    Method batteryMethod = BluetoothDevice.class.getDeclaredMethod("getBatteryLevel", (Class[]) null);
                    batteryMethod.setAccessible(true);
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    isConnectedMethod.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    int level = (int) batteryMethod.invoke(device, (Object[]) null);
                    if (device != null && level > 0 && isConnected) {
                        String deviceName = device .getName();
                        battery = level;
                        android.util.Log.i(TAG, "Connected Bluetooth="+deviceName + "  battery="+level);
                    }
                }
            } else {
                android.util.Log.e(TAG, "No Connected Bluetooth Devices Found");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            return battery;
        }
    }

电量值为 -1 说明蓝牙设备不支持读取电量


其实后来通过跟踪系统蓝牙连接界面显示电量值逻辑,最终找到的也是调用此方法获取电量


frameworks\base\packages\SettingsLib\src\com\android\settingslib\bluetooth\CachedBluetoothDevice.java


 /**
     * Return summary that describes connection state of this device. Summary depends on:
     * 1. Whether device has battery info
     * 2. Whether device is in active usage(or in phone call)
     *
     * @param shortSummary {@code true} if need to return short version summary
     */
    public String getConnectionSummary(boolean shortSummary) {
        boolean profileConnected = false;    // Updated as long as BluetoothProfile is connected
        boolean a2dpConnected = true;        // A2DP is connected
        boolean hfpConnected = true;         // HFP is connected
        boolean hearingAidConnected = true;  // Hearing Aid is connected
        int leftBattery = -1;
        int rightBattery = -1;
    .....
     String batteryLevelPercentageString = null;
        // Android framework should only set mBatteryLevel to valid range [0-100] or
        // BluetoothDevice.BATTERY_LEVEL_UNKNOWN, any other value should be a framework bug.
        // Thus assume here that if value is not BluetoothDevice.BATTERY_LEVEL_UNKNOWN, it must
        // be valid
        final int batteryLevel = getBatteryLevel();
        if (batteryLevel != BluetoothDevice.BATTERY_LEVEL_UNKNOWN) {
            // TODO: name com.android.settingslib.bluetooth.Utils something different
            batteryLevelPercentageString =
                    com.android.settingslib.Utils.formatPercentage(batteryLevel);
        }
        int stringRes = R.string.bluetooth_pairing;
        //when profile is connected, information would be available
        if (profileConnected) {
            // Update Meta data for connected device
            if (BluetoothUtils.getBooleanMetaData(
                    mDevice, BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET)) {
                leftBattery = BluetoothUtils.getIntMetaData(mDevice,
                        BluetoothDevice.METADATA_UNTETHERED_LEFT_BATTERY);
                rightBattery = BluetoothUtils.getIntMetaData(mDevice,
                        BluetoothDevice.METADATA_UNTETHERED_RIGHT_BATTERY);
            }
    ......
}
 /**
     * Get battery level from remote device
     * @return battery level in percentage [0-100], or {@link BluetoothDevice#BATTERY_LEVEL_UNKNOWN}
     */
    public int getBatteryLevel() {
  //android.bluetooth.BluetoothDevice  mDevice;
        return mDevice.getBatteryLevel();
    }

通过跟踪发现控制蓝牙图标显示代码在 PhoneStatusBarPolicy.java 中,只有当蓝牙设备连接成功后蓝牙图标才会显示,


默认用的资源文件为 stat_sys_data_bluetooth_connected.xml,我们就可以在这块做调整,当蓝牙设备连接成功后读取电量值,


根据电量值获取对应电池格数资源文件就ok了。


vendor/mediatek/proprietary/packages/apps/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java

 @Override
    public void onBluetoothStateChange(boolean enabled) {
        updateBluetooth();
    }
    private final void updateBluetooth() {
        //int iconId = R.drawable.stat_sys_data_bluetooth_connected;
        int iconId = R.drawable.ic_bluetooth_connected_super;//cczheng change
        String contentDescription =
                mContext.getString(R.string.accessibility_quick_settings_bluetooth_on);
        boolean bluetoothVisible = false;
        if (mBluetooth != null) {
            if (mBluetooth.isBluetoothConnected()) {
                contentDescription = mContext.getString(R.string.accessibility_bluetooth_connected);
                bluetoothVisible = mBluetooth.isBluetoothEnabled();
            }
        }
        //20200602 cczheng add
        if (bluetoothVisible) {
            int battery = getBluetoothDeviceBattery();
            if (battery > 0) {
                iconId = getBatteryLevelIconId(battery);
            }
        }//E
        mIconController.setIcon(mSlotBluetooth, iconId, contentDescription);
        mIconController.setIconVisibility(mSlotBluetooth, bluetoothVisible);
    }
    //20200602 cczheng add for show bt headset battery S
    private int getBatteryLevelIconId(int battery){
        int iconId = 0;
        if (battery <= 10) {
            iconId = R.drawable.stat_sys_data_bluetooth_connected_battery_0;
        }else if (battery <= 20) {
            iconId = R.drawable.stat_sys_data_bluetooth_connected_battery_1;
        }else if (battery <= 40) {
            iconId = R.drawable.stat_sys_data_bluetooth_connected_battery_2;
        }else if (battery <= 60) {
            iconId = R.drawable.stat_sys_data_bluetooth_connected_battery_3;
        }else if (battery <= 80) {
            iconId = R.drawable.stat_sys_data_bluetooth_connected_battery_4;
        }else if (battery <= 100) {
            iconId = R.drawable.stat_sys_data_bluetooth_connected_battery_5;
        }
        Log.e(TAG, "iconId="+iconId);
        return iconId;
    }
    private  int getBluetoothDeviceBattery(){
        int battery = -1;
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;
        try {
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            method.setAccessible(true);
            int state = (int) method.invoke(btAdapter, (Object[]) null);
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                for (BluetoothDevice device : devices) {
                    Method batteryMethod = BluetoothDevice.class.getDeclaredMethod("getBatteryLevel", (Class[]) null);
                    batteryMethod.setAccessible(true);
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    isConnectedMethod.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    int level = (int) batteryMethod.invoke(device, (Object[]) null);
                    if (device != null && level > 0 && isConnected) {
                        String deviceName = device .getName();
                        battery = level;
                        android.util.Log.i(TAG, "Connected Bluetooth="+deviceName + "  battery="+level);
                    }
                }
            } else {
                android.util.Log.e(TAG, "No Connected Bluetooth Devices Found");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            return battery;
        }
    }
    //20200602 cczheng add for show bt headset battery E
    private final void updateTTY() {
        TelecomManager telecomManager =
                (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
        if (telecomManager == null) {
            updateTTY(TelecomManager.TTY_MODE_OFF);
        } else {
            updateTTY(telecomManager.getCurrentTtyMode());
        }
    }

参考文章


Android 10 获取已连接的蓝牙设备的当前电量

Android7.0 获取蓝牙设备电量

目录
相关文章
|
Unix Linux iOS开发
振南技术干货集:各大平台串口调试软件大赏(4)
振南技术干货集:各大平台串口调试软件大赏(4)
|
程序员 uml
【程序员小知识】使用PlantUML画UML(下) 时序图
【程序员小知识】使用PlantUML画UML(下) 时序图
1411 0
|
开发者
为什么你的游戏做不出来?
为什么你的游戏做不出来?
395 0
|
1月前
|
人工智能 安全 测试技术
2026 年 GPT-6 Astra 能力测评文档:跨任务性能升级、实操案例,多模型横向评测数据解析
OpenAI对外推出新一代旗舰大模型GPT‑6 Astra,官方将它定义为全世界智能水平最高、对齐效果最好的AI模型。在发布前的媒体闭门沟通会上,OpenAI总裁Greg Brockman抛出一句引发整个行业热烈讨论的观点:如今认为人类已经踏入AGI时代,已经算不上是异想天开的想法,欢迎大家来到AGI时代。这句话迅速传遍开发者圈子,也让GPT‑6 Astra成为全球AI领域焦点。但不少第一时间想要体验新模型的用户打开客户端之后发现,不管是网页对话界面还是API接口,都找不到GPT‑6 Astra的入口。按照官方公布的推送节奏,Astra初期仅向一小批安全研究机构、受信任的合作组织开放访问权限,
347 0
|
2月前
|
人工智能 Ubuntu Linux
CC Switch怎么用:添加供应商、一键切换全攻略(全网最详细)
CC Switch 是一款免费开源的桌面工具,专为统一管理 AI 编程工具(如 Claude Code、Codex、Gemini CLI)的 API 供应商而设计。它提供图形化界面,支持一键切换官方/中转/自建供应商,集成 MCP、提示词、Skills 管理及用量统计,大幅简化配置流程。(239字)
|
10月前
|
弹性计算 监控 大数据
阿里云国外地域云服务器收费标准、购买流程与选择和使用注意事项参考
阿里云国外云服务器是外贸企业的理想选择,覆盖亚太、欧洲、美洲、中东等多个地区,确保业务快速响应。提供按量、按月、包年等多样计费方式,满足不同需求。其优势在于全球覆盖、灵活计费、高性能计算及稳定网络,适合外贸企业、免备案应用、大数据处理、游戏娱乐等多种场景。阿里云提供高数据可靠性保障,结合促销活动、优惠券和续费同价政策,助力用户低成本高效运营。
3699 8
|
数据库管理
SVN 执行cleanup报错:Cleanup failed to process the following paths : 解决方法
引用:https://www.cnblogs.com/pinpin/p/11395438.html 在SVN更新时提示文件被锁住了,要求执行 clean up操作,执行clean up时又报clean up failed。造成的原因是在某次更新后,点击了cancel按钮,操作没有完成所以会锁住。解决方法如下:
3612 0
|
XML Java Android开发
Android关于BottomNavigationView效果实现指南
本文详细介绍了Android中BottomNavigationView的实现与定制方法,涵盖颜色设置、图标修改、字体大小调整及多色图标处理等问题。通过XML和Java代码两种方式,解决图标颜色变化、点击效果等问题,并提供去除ActionBar的实现步骤。适合初学者及进阶开发者参考,助力打造更美观、功能丰富的底部导航栏。文末附源码,方便实践操作。
1435 28
Android关于BottomNavigationView效果实现指南
怎样将Beyond Compare添加到系统右键菜单
怎样将Beyond Compare添加到系统右键菜单
3526 0
|
SQL Oracle 关系型数据库
Navicat还原DMP文件步骤
Navicat还原DMP文件步骤
1415 13