使用Android Studio 2.2和CMake在Android中编译和使用依赖于ABI的可执行二进制文件

时间:2016-08-12 11:51:50

标签: android android-studio gradle android-ndk cmake

我正在通过CMake通过稳定的gradle(http://tools.android.com/tech-docs/external-c-builds)测试新的Android Studio C / C ++构建。

在我的应用中,已经植根的设备需要使用我在Android Studio中编译的依赖于ABI的二进制文件。

当我尝试使用

编译标准库时
add_library(mylib SHARED mylib.c)

它会自动编译并复制到APK的lib / [ABI]文件夹中(例如/lib/armeabi/mylib.so)但如果我用以下代码编译可执行二进制文件:

add_executable(mybinary mybinary.cpp)

在构建文件夹中生成二进制文件:

app/build/intermediates/cmake/debug/lib/armeabi/mybinary
app/build/intermediates/cmake/debug/lib/x86_64/mybinary 
...

但它们似乎没有复制到apk内的任何地方。

处理这种需求的正确方法是什么?草地任务是可行的吗?

的build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.my.app"
        minSdkVersion 10
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild{
        cmake{
            path "CMakeLists.txt"
        }
    }

    defaultConfig {
        externalNativeBuild {
            cmake {
                targets "
                arguments "-DANDROID_TOOLCHAIN=clang", "-DANDROID_PLATFORM=android-21"
                cFlags "-DTEST_C_FLAG1", "-DTEST_C_FLAG2"
                cppFlags "-DTEST_CPP_FLAG2", "-DTEST_CPP_FLAG2"
                abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a'
            }
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:recyclerview-v7:24.1.1'
    compile 'eu.chainfire:libsuperuser:1.0.0.201607041850'
}

的CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)

set(CMAKE_VERBOSE_MAKEFILE on)

add_executable(mybinary ${CMAKE_CURRENT_SOURCE_DIR}/mybinary.cpp)
target_link_libraries( mybinary libcustom)
target_include_directories (mybinary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

mybinary.cpp

#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {

    string hello = "Hello from C++";
    cout << "Message from native code: " << hello << "\n";

    return EXIT_SUCCESS;
}

应用如何与mybinary互动:

import eu.chainfire.libsuperuser.Shell;
...
Shell.SU.run("/path/to/mybinary");

2 个答案:

答案 0 :(得分:16)

好的,我找到了一个似乎相当舒服的解决方案,但可能还有更合适的方法;

默认情况下,CMakeLists.txt放在myAppProject / app中,所以我已将此行添加到CMakeLists.txt:

set(EXECUTABLE_OUTPUT_PATH      "${CMAKE_CURRENT_SOURCE_DIR}/src/main/assets/${ANDROID_ABI}")

完整app / CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.1)

set(CMAKE_VERBOSE_MAKEFILE on)

# set binary output folder to Android assets folder
set(EXECUTABLE_OUTPUT_PATH      "${CMAKE_CURRENT_SOURCE_DIR}/src/main/assets/${ANDROID_ABI}")

add_subdirectory (src/main/cpp/mylib)
add_subdirectory (src/main/cpp/mybinary)

完成app / src / main / cpp / mybinary / CMakeLists.txt:

add_executable(mybinary ${CMAKE_CURRENT_SOURCE_DIR}/mybinary.cpp)
# mybinary, in this example, has mylib as dependency
target_link_libraries( mybinary mylib)
target_include_directories (mybinary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

完成app / src / main / cpp / mylib / CMakeLists.txt:

add_library( # Sets the name of the library.
             mylib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             # Associated headers in the same location as their source
             # file are automatically included.
             ${CMAKE_CURRENT_SOURCE_DIR}/mylib.cpp )

target_include_directories (mylib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

这样做,任何可执行二进制文件都直接编译到assets文件夹中,在名为目标ABI的子文件夹中,例如:

assets/armeabi/mybinary
assets/x86_64/mybinary
... 

为了在App中使用正确的二进制文件,应选择正确的二进制文件:

String abi;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    abi = Build.SUPPORTED_ABIS[0];
} else {
    //noinspection deprecation
    abi = Build.CPU_ABI;
}
String folder;
if (abi.contains("armeabi-v7a")) {
    folder = "armeabi-v7a";
} else if (abi.contains("x86_64")) {
    folder = "x86_64";
} else if (abi.contains("x86")) {
    folder = "x86";
} else if (abi.contains("armeabi")) {
    folder = "armeabi";
}
...
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(folder+"/" + "mybinary");

然后,应该使用正确的执行权限将二进制文件从assets文件夹中复制出来:

OutputStream out = context.openFileOutput("mybinary", MODE_PRIVATE);
long size = 0;
int nRead;
while ((nRead = in.read(buff)) != -1) {
    out.write(buff, 0, nRead);
    size += nRead;
}
out.flush();
Log.d(TAG, "Copy success: " +  " + size + " bytes");
File execFile = new File(context.getFilesDir()+"/mybinary");
execFile.setExecutable(true);

这就是全部!

更新: gradle.build文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25"
    defaultConfig {
        applicationId "com.myapp.example"
        minSdkVersion 10
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }

    defaultConfig {
        externalNativeBuild {
            cmake {
                targets "mylib", "mybinary"
                arguments "-DANDROID_TOOLCHAIN=clang"
                cFlags "-DTEST_C_FLAG1", "-DTEST_C_FLAG2"
                cppFlags "-DTEST_CPP_FLAG2", "-DTEST_CPP_FLAG2"
                abiFilters 'armeabi', 'armeabi-v7a', 'x86', 'x86_64'
            }
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'eu.chainfire:libsuperuser:1.0.0.201607041850'
}

答案 1 :(得分:3)

  1. 将可执行文件输出到Android Gradle插件所需库的位置:

    set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")

  2. 傻瓜该插件认为您的可执行文件是一个共享对象:

    add_executable(i_am_an_executable.so main.c)

  3. 检查APK:

    $ 7z l build/outputs/apk/app-debug.apk lib/                                                                                                                                    [2:08:56]
       Date      Time    Attr         Size   Compressed  Name
    ------------------- ----- ------------ ------------  ------------------------
                        .....         9684         4889  lib/armeabi/i_am_an_executable.so
                        .....         6048         1710  lib/arm64-v8a/i_am_an_executable.so
                        .....         9688         4692  lib/armeabi-v7a/i_am_an_executable.so
                        .....         5484         1715  lib/x86/i_am_an_executable.so
                        .....         6160         1694  lib/x86_64/i_am_an_executable.so
    
  4. 访问并运行您的可执行文件;它位于context.getApplicationInfo().nativeLibraryDir

这样做的缺点是您无法将android:extractNativeLibs设置为false - 我不知道如何在应用内从APK中访问lib/