【问题标题】:what is the best way to interface a shell script to an android application?将 shell 脚本连接到 android 应用程序的最佳方式是什么?
【发布时间】:2014-02-27 02:47:03
【问题描述】:

目前我有使用终端模拟器应用程序在 android 上运行的 shell 脚本命令。需要准备一个应用程序以从我的 android 应用程序调用 shell 脚本,在我的应用程序上显示 shell 脚本的结果。任何人都可以提出最好的方法来做到这一点。

【问题讨论】:

标签: android api shell


【解决方案1】:

使用的代码来自here

    public void runShellCommand(String[] cmds) throws Exception {
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        InputStream is = p.getInputStream();
        for (String temp : cmds) {
            os.writeBytes(temp+"\n");
            int read= 0;
            byte[] buff = new byte[4096];

        // if cmd requires an output
       // due to the blocking behaviour of read(...)
        boolean cmdRequiresAnOutput = true;
        if (cmdRequiresAnOutput) {
            while( is.available() <= 0) {
                try { Thread.sleep(200); } catch(Exception ex) {}
            }

            while( is.available() > 0) {
                read = is.read(buff);
                if ( read <= 0 ) break;
                String str = new String(buff,0,read);
                console.println("#> "+str);
        }
    }
}        
os.writeBytes("exit\n");
os.flush();
}

使用时间长的命令需要休眠。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2019-04-29
    • 2018-05-12
    • 2012-02-09
    • 1970-01-01
    • 2022-06-28
    相关资源
    最近更新 更多