准备
开发某些系统app 的时候,需要在代码里面设置adb命令,获取一些信息。 首先要确保应用是系统应用,然后就是添加权限。某些命令需要系统权限才能获取,也不是全部。看实际的使用情况。
android:sharedUserId=“android.uid.system” uses-permission android:name=“android.permission.DUMP”
执行adb的代码逻辑
public class FileManager {
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
);
process
.waitFor();
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
) {
}
}
}
}
实际使用
使用命令时不需要添加 adb shell
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
);