首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在android中以编程方式使用blktrace命令执行shell脚本?

如何在android中以编程方式使用blktrace命令执行shell脚本?
EN

Stack Overflow用户
提问于 2021-02-04 10:09:21
回答 1查看 141关注 0票数 0

我有一个有根有肉的android设备,里面安装了blktrace。我想要执行一个shell脚本来测试我的应用程序中的blktrace。我已经尝试了一些解决方案,从一些资源从互联网。我已经尝试过这两种方法来执行shell脚本。

方法1

代码语言:javascript
复制
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

代码语言:javascript
复制
 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命令,如下面所示,并显示预期的输出。

代码语言:javascript
复制
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这样的命令?

EN

回答 1

Stack Overflow用户

发布于 2021-02-04 14:51:16

我认为您的命令需要这样的字符串数组。

代码语言:javascript
复制
    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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66043443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档