如何在Android应用程序运行终端命令? [英] How to run terminal command in Android application?

查看:227
本文介绍了如何在Android应用程序运行终端命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过Android应用程序发送一个命令到终端并获得输出反馈?例如,发送LS /和获取输出到GUI打印?

How to send a command to the terminal through android app and get the output back? For example, sending "ls /" and getting the output to print it in the GUI?

推荐答案

您必须使用反射来调用android.os.Exec.createSubprocess():

You have to use reflection to call android.os.Exec.createSubprocess():

public String ls () {
    Class<?> execClass = Class.forName("android.os.Exec");
    Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
    int[] pid = new int[1];
    FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/ls", "/", null, pid);

    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
    String output = "";
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            output += line + "\n";
        }
    }
    catch (IOException e) {}
    return output;
}

这篇关于如何在Android应用程序运行终端命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆