Android使用代码方式获取部分adb信息 您所在的位置:网站首页 执行adb命令软件 Android使用代码方式获取部分adb信息

Android使用代码方式获取部分adb信息

2023-09-18 04:33| 来源: 网络整理| 查看: 265

准备

开发某些系统app 的时候,需要在代码里面设置adb命令,获取一些信息。 首先要确保应用是系统应用,然后就是添加权限。某些命令需要系统权限才能获取,也不是全部。看实际的使用情况。

android:sharedUserId=“android.uid.system” uses-permission android:name=“android.permission.DUMP”

执行adb的代码逻辑 public class FileManager { /** * 执行系统命令, 返回执行结果 * * @param cmd 需要执行的命令 * @param dir 执行命令的子进程的工作目录, null 表示和当前主进程工作目录相同 */ public static String execCmd(String cmd, File dir) throws Exception { StringBuilder result = new StringBuilder(); Process process = null; BufferedReader bufrIn = null; BufferedReader bufrError = null; try { // 执行命令, 返回一个子进程对象(命令在子进程中执行) process = Runtime.getRuntime().exec(cmd, null, dir); // 方法阻塞, 等待命令执行完成(成功会返回0) process.waitFor(); // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入) bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8")); // 读取输出 String line = null; while ((line = bufrIn.readLine()) != null) { result.append(line).append('\n'); } while ((line = bufrError.readLine()) != null) { result.append(line).append('\n'); } } finally { closeStream(bufrIn); closeStream(bufrError); if (process != null) { process.destroy(); } } // 返回执行结果 return result.toString(); } private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (Exception e) { // nothing } } } } 实际使用

使用命令时不需要添加 adb shell

//获取cpu信息 String fileData = FileManager.execCmd("dumpsys cpuinfo", null); Logger.d(TAG, "CPU DATA :" + fileData); //获取内存使用信息 String fileData = FileManager.execCmd("dumpsys meminfo", null); Logger.d(TAG, "meminfo DATA :" + fileData); //获取挂载信息 String fileData = FileManager.execCmd("df data", null); String filePersist = FileManager.execCmd("df persist", null); Logger.d(TAG, "df DATA :" + fileData); Logger.d(TAG, "df Persist :" + filePersist);


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有