android - 是否可以在非 root 的 android 手机上运行 native arm 二进制文件?

标签 android android-ndk arm root codesourcery

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

最佳答案

Update: notice that apps targeting API level 29 (Android 10) and above will not be able to use the trick below, as the OS will restrict the execute permission. See Behavior changes: apps targeting API 29+.

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

您必须在应用程序的 assets 文件夹中包含所有必要的文件。为了运行它们,您必须让程序将它们从 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();

关于android - 是否可以在非 root 的 android 手机上运行 native arm 二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4703131/

相关文章:

android - SurfaceView 实现 Runnable - 线程不启动

java - Ant 释放--> Ant : command not found

用于arm-linux的浮点SQlite3问题

android - Gradle 有错误,但构建良好

android - 动态创建/绘制图像以放入 android View

Android OpenCV 与 JNI 性能不佳

android - 系统/fcntl.h : no such file while cross compiling pcsclite for Android?

c - 使用 arm-linux-gnueabi-gcc 交叉编译 ARMv6l 的标志

Linux Booting Angel 开机

android - 由于无效原因,我的应用被 Instagram Basic Display API 审核拒绝