簡體   English   中英

如何以編程方式在 android 中使用 blktrace 命令執行 shell 腳本?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM