[英]How to execute shell scripts with blktrace commands in android programmatically?
I have a rooted android device with blktrace installed in it.我有一个根植于 android 设备,其中安装了 blktrace。 I want to execute a shell script for testing blktrace from my application.
我想执行一个 shell 脚本来测试我的应用程序中的 blktrace。 I have tried some solutions found in some resources from internet.
我尝试了一些在互联网上的一些资源中找到的解决方案。 I have tried these two methods for executing shell scripts
我试过这两种方法来执行 shell 脚本
Method 1方法一
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()
}
Method 2方法二
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
}
These methods works fine with shell commands like below and show expected outputs这些方法适用于 shell 命令,如下所示并显示预期输出
ls /sdcard/
cat /proc/cpuinfo
I want to execute some commands like blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs
but it doesn't execute via my app.我想执行一些命令,例如
blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs
但它不会通过我的应用程序执行。 But I can execute this command perfectly via adb shell with su root permission.但是我可以通过具有 su root 权限的 adb shell 完美地执行此命令。
How can I execute commands like blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs
from my app?如何从我的应用程序执行
blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs
类的命令?
I think you need something like this array of strings for your command.我认为您的命令需要类似这样的字符串数组。
private static final String processId = Integer.toString(android.os.Process
.myPid());
String[] command = new String[] { "logcat", "-d", "threadtime" };
Process process = Runtime.getRuntime().exec(command);
My answer can be found here: https://stackoverflow.com/a/37720611/3806413我的答案可以在这里找到: https://stackoverflow.com/a/37720611/3806413
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.