Any way to run shell commands on android programmatically?

Viewed 94296

Is there any way to run terminal commands on my application and then access the data on my UI? Specifically top.

5 Answers

For Kotlin enthusiasts, you can use the following

fun executeShell() {
    val command: String = "top -n 1"
    try {
        val process: Process = Runtime.getRuntime().exec(command)
        // Read the lines using BufferedReader
        BufferedReader(InputStreamReader(process.inputStream)).forEachLine {
            // Do something on each line read
            Log.d(this::class.java.canonicalName, "$it")
        }
    } catch (e: InterruptedException) {
        Log.w(this::class.java.canonicalName, "Cannot execute command [$command].", e)
    } catch (e: Exception) {
        Log.e(this::class.java.canonicalName, "Cannot execute command [$command].", e)
    }
}

You won't even have to take care of closing the buffer, as forEachLine extension function takes care of it.

Related