簡體   English   中英

任何以編程方式在android上運行shell命令的方法?

[英]Any way to run shell commands on android programmatically?

有沒有辦法在我的應用程序上運行終端命令,然后訪問我的 UI 上的數據? 具體top

以日志收集器為例。 這是相關文件

關鍵在這里:

ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat");//$NON-NLS-1$
[...]

Process process = Runtime.getRuntime().exec(commandLine);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

好的,這對我有用,以防將來有人需要它...... :)

圍繞嘗試和捕捉

try {
    Process process = Runtime.getRuntime().exec("top -n 1 -d 1");
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
} catch (InterruptedException e) {
    e.printStackTrace();
}

我們,可以執行如下命令,我成功地做到了......! 試試這樣,這里我們需要指定命令的完整路徑。 獲取命令的完整路徑,在你的終端(android)輸入

*$ which ls

/系統/斌*

try {

    // Executes the command.

    Process process = Runtime.getRuntime().exec("/system/bin/ls /sdcard");

    // Reads stdout.
    // NOTE: You can write to stdin of the command using
    //       process.getOutputStream().
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    int read;
    char[] buffer = new char[4096];
    StringBuffer output = new StringBuffer();
    while ((read = reader.read(buffer)) > 0) {
        output.append(buffer, 0, read);
    }
    reader.close();

    // Waits for the command to finish.
    process.waitFor();

    return output.toString();
} catch (IOException e) {

    throw new RuntimeException(e);

} catch (InterruptedException e) {

    throw new RuntimeException(e);
}

它還取決於您在終端中運行的內容……如果您在文件上運行“cat”,您也可以這樣做。

final private String MEM_FILE = "/proc/meminfo";

public Long readMem() {
    String[] segs;
    FileReader fstream;
    try {
        fstream = new FileReader(MEM_FILE);
    } catch (FileNotFoundException e) {
        Log.e("readMem", "Could not read " + MEM_FILE);
        return false;
    }
    BufferedReader in = new BufferedReader(fstream, 500);
    String line;
    try {
        while ((line = in.readLine()) != null) {
            if (line.indexOf("MemTotal:") > 0) {
                Log.e("MemTotal", line);
                segs = line.trim().split("[ ]+");
                memTotal = Long.parseLong(segs[1]);
            }
            if (line.indexOf("MemFree:") > 0) {
                Log.e("MemFree", line);
                segs = line.trim().split("[ ]+");
                memFree = Long.parseLong(segs[1]);
            }
        }
        updateMem(); //call function to update textviews or whatever
        return true;
    } catch (IOException e) {
        Log.e("readMem", e.toString());
    }
    return false;
}

編輯:在名為 netmeter 的 android 實驗室項目中有一個完美的例子。 有一個名為 Top.java 的類實際上完全符合您的要求,它在 TaskList.java 中用於顯示。 http://code.google.com/p/android-labs/source/browse/#svn/trunk/NetMeter/src/com/google/android/netmeter

對於 Kotlin 愛好者,可以使用以下

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)
    }
}

您甚至不必關閉緩沖區,因為forEachLine擴展函數會處理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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