您好,欢迎来到外链网!
当前位置:外链网 » 站长资讯 » 专业问答 » 文章详细 订阅RssFeed

Android 通过代码执行shell命令获取电量百分比

来源:互联网 浏览:139次 时间:2023-04-08

shell 执行?adb shell dumpsys battery 命令,得到如下信息:

获取shell命令的返回值内容(以下 new ExeCommand().run("dumpsys battery \n", 3000).getResult();部分),可以参考这篇文章:https://www.cnblogs.com/lipeineng/p/6078859.html

关键之如何获取scale:100中的数字部分?

可以通过正则表达式:

//获取电量private String getBatteryLevel() { String res = ""; String lines = new ExeCommand().run("dumpsys battery \n", 3000).getResult(); String pattern = "scale: (\\d)*"; //创建Pattern对象 Pattern p = Pattern.compile(pattern);便宜香港vps //创建Matcher对象 Matcher m = p.matcher(lines); if (m.find()) { res = m.group(0).split(":")[1].trim(); } return res;} 68435324