我有一个有根有肉的android设备,里面安装了blktrace。我想要执行一个shell脚本来测试我的应用程序中的blktrace。我已经尝试了一些解决方案,从一些资源从互联网。我已经尝试过这两种方法来执行shell脚本。
方法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()
}方法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
}这些方法适用于shell命令,如下面所示,并显示预期的输出。
ls /sdcard/
cat /proc/cpuinfo我想执行一些命令,如blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs,但它不执行通过我的应用程序。但是,我可以通过亚行shell和su root权限完美地执行这个命令。
如何从我的应用程序中执行像blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs这样的命令?
发布于 2021-02-04 14:51:16
我认为您的命令需要这样的字符串数组。
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
https://stackoverflow.com/questions/66043443
复制相似问题