在Android错误中运行本机可执行文件

时间:2010-09-24 02:27:07

标签: java android

我试图使用下面的代码来运行本机,我在类execClass = Class.forName(“android.os.Exec”)中得到了android.os.exec的classnotfoundexception ..任何想法y?

    try {
    // android.os.Exec is not included in android.jar so we need to use reflection.
    Class<?> execClass = Class.forName("android.os.Exec");
    Method createSubprocess = execClass.getMethod("createSubprocess",
            String.class, String.class, String.class, int[].class);
    Method waitFor = execClass.getMethod("waitFor", int.class);

    // Executes the command.
    // NOTE: createSubprocess() is asynchronous.
    int[] pid = new int[1];
    FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(
            null, "/system/bin/ls", "/sdcard", null, pid);

    // Reads stdout.
    // NOTE: You can write to stdin of the command using new FileOutputStream(fd).
    FileInputStream in = new FileInputStream(fd);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String output = "";
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            output += line + "\n";
        }
    } catch (IOException e) {
        // It seems IOException is thrown when it reaches EOF.
    }

    // Waits for the command to finish.
    waitFor.invoke(null, pid[0]);

    return output;
} catch (ClassNotFoundException e) {
    throw new RuntimeException(e.getMessage());
} catch (SecurityException e) {
    throw new RuntimeException(e.getMessage());
} catch (NoSuchMethodException e) {
    throw new RuntimeException(e.getMessage());
} catch (IllegalArgumentException e) {
    throw new RuntimeException(e.getMessage());
} catch (IllegalAccessException e) {
    throw new RuntimeException(e.getMessage());
} catch (InvocationTargetException e) {
    throw new RuntimeException(e.getMessage());
}

链接:http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App

1 个答案:

答案 0 :(得分:2)

android.os.Exec不是公共API的一部分,不应该使用。自1.6以来它不属于产品的这一事实应该是进一步的激励。 : - )

您应该使用标准的Java语言工具,例如Runtime.exec()或ProcessBuilder.start()。