20

好吧,我一直在低级 Android 编程(使用 CodeSourcery 工具链的原生 C/C++)的浑水中潜水。我在模拟器上试用了可执行文件,它工作正常。我想在真实设备上试用一下。所以我插入了我的关系并将文件推送到文件系统。然后我尝试执行二进制文件,但出现权限错误。我如何安装它或将它发送到哪里真的无关紧要,我不是 root 并且它不允许我执行它。有没有办法在非root手机上运行这样的程序?

4

1 回答 1

40

使用 Android NDK 中包含的工具链编译二进制文件后,可以将它们与典型的 Android 应用程序打包,并将它们作为子进程生成。

您必须在应用程序的 assets 文件夹中包含所有必要的文件。为了运行它们,您必须让程序将它们从资产文件夹复制到可运行的位置,例如:/data/data/com.yourdomain.yourapp/nativeFolder

你可以这样做:

private static void copyFile(String assetPath, String localPath, Context context) {
    try {
        InputStream in = context.getAssets().open(assetPath);
        FileOutputStream out = new FileOutputStream(localPath);
        int read;
        byte[] buffer = new byte[4096];
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.close();
        in.close();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

请记住,assetPath 不是绝对的,而是相对于 assets/.

IE:“assets/nativeFolder”只是“nativeFolder”

然后运行您的应用程序并读取其输出,您可以执行以下操作:

  Process nativeApp = Runtime.getRuntime().exec("/data/data/com.yourdomain.yourapp/nativeFolder/application");


            BufferedReader reader = new BufferedReader(new InputStreamReader(nativeApp.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.
            nativeApp.waitFor();

            String nativeOutput =  output.toString();
于 2011-07-23T21:01:19.170 回答