将go项目交叉编译到Android上运行

编译

编译32位版本:

env GOOS=android GOARCH=arm CC=/path/to/android/sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/darwin-x86_64/bin/armv7a-linux-androideabi30-clang GOARM=7 CGO_ENABLED=1 go build -v .

编译64位版本:

env GOOS=android GOARCH=arm64 CC=/path/to/android/sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android30-clang GOARM=7 CGO_ENABLED=1 go build -v .

不能用22版本的ndk,会导致编译失败

https://github.com/golang/go/issues/42725

编译后的二进制文件放到assets文件夹中

提取

将assets文件夹中的二进制文件,提取到app的私有file目录中,并授予执行权限

try {
    String path = getFilesDir().getAbsolutePath();
    System.out.println(path);
    InputStream inputStream = getAssets().open(name);
    FileOutputStream fileOutputStream = new FileOutputStream(path + File.separator + name);
    byte[] buffer = new byte[1024];
    int byteCount = 0;
    while ((byteCount = inputStream.read(buffer)) != -1) {// 循环从输入流读取
        // buffer字节
        fileOutputStream.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
    }
    fileOutputStream.flush();// 刷新缓冲区
    inputStream.close();
    fileOutputStream.close();

    runCmd("/system/bin/chmod 744 " + path + File.separator + name);
} catch (IOException e) {
    e.printStackTrace();
}

运行

添加环境变量并运行命令

String[] a = cmd.split(" ");
String path = getFilesDir().getAbsolutePath();
ProcessBuilder processBuilder = new ProcessBuilder(a);
final Map<String, String> environment = processBuilder.environment();
String pathEnv = environment.get("PATH");
if (pathEnv == null) {
    environment.put("PATH", path + File.separator);
} else {
    pathEnv += (":" + path + File.separator);
    environment.put("PATH", pathEnv);
}
processBuilder.directory(new File(path + File.separator));
Process process = processBuilder.start();

InputStream reader = process.getInputStream();
int read;
byte[] buffer = new byte[4096];
while ((read = reader.read(buffer)) > 0) {
    superHandler.obtainMessage(1, 0, read, buffer).sendToTarget();
}
reader.close();

// Waits for the command to finish.
process.waitFor();
return;
Share

You may also like...

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注