[英]How to execute shell scripts with blktrace commands in android programmatically?
我有一个根植于 android 设备,其中安装了 blktrace。 我想执行一个 shell 脚本来测试我的应用程序中的 blktrace。 我尝试了一些在互联网上的一些资源中找到的解决方案。 我试过这两种方法来执行 shell 脚本
方法一
fun executeShell(): String {
val output = StringBuffer()
val p: Process
try {
p = Runtime.getRuntime().exec("path/to/script/file")
p.waitFor()
val reader =
BufferedReader(InputStreamReader(p.inputStream))
var line = ""
while (reader.readLine().also { line = it } != null) {
output.append(line + "n")
}
} catch (e: Exception) {
e.printStackTrace()
}
return output.toString()
}
方法二
private fun runAsRoot():Boolean {
try {
// Executes the command. /data/app/test.sh
val process = Runtime.getRuntime().exec("path/to/shellscript/file")
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
val reader = BufferedReader(
InputStreamReader(process.inputStream)
)
var read: Int
val buffer = CharArray(4096)
val output = StringBuffer()
while (reader.read(buffer).also { read = it } > 0) {
output.append(buffer, 0, read)
}
reader.close()
// Waits for the command to finish.
process.waitFor()
output.toString()
Log.e("output", "OUT " + output.toString()).toString()
isShellRun = true
} catch (e: IOException) {
isShellRun = false
throw RuntimeException(e)
} catch (e: InterruptedException) {
isShellRun = false
throw RuntimeException(e)
}
return isShellRun
}
这些方法适用于 shell 命令,如下所示并显示预期输出
ls /sdcard/
cat /proc/cpuinfo
我想执行一些命令,例如blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs
但它不会通过我的应用程序执行。 但是我可以通过具有 su root 权限的 adb shell 完美地执行此命令。
如何从我的应用程序执行blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs
类的命令?
我认为您的命令需要类似这样的字符串数组。
private static final String processId = Integer.toString(android.os.Process
.myPid());
String[] command = new String[] { "logcat", "-d", "threadtime" };
Process process = Runtime.getRuntime().exec(command);
我的答案可以在这里找到: https://stackoverflow.com/a/37720611/3806413
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.