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

ADD*_*ADD 15 android cmake gradle android-ndk android-studio

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

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

当我尝试编译标准库时

add_library(mylib SHARED mylib.c)
Run Code Online (Sandbox Code Playgroud)

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

add_executable(mybinary mybinary.cpp)
Run Code Online (Sandbox Code Playgroud)

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

app/build/intermediates/cmake/debug/lib/armeabi/mybinary
app/build/intermediates/cmake/debug/lib/x86_64/mybinary 
...
Run Code Online (Sandbox Code Playgroud)

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

处理这种需求的正确方法是什么?gradle-task是要走的路吗?

的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'
}
Run Code Online (Sandbox Code Playgroud)

的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})
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

应用程序应如何与mybinary交互:

import eu.chainfire.libsuperuser.Shell;
...
Shell.SU.run("/path/to/mybinary");
Run Code Online (Sandbox Code Playgroud)

ADD*_*ADD 17

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

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

set(EXECUTABLE_OUTPUT_PATH      "${CMAKE_CURRENT_SOURCE_DIR}/src/main/assets/${ANDROID_ABI}")
Run Code Online (Sandbox Code Playgroud)

完整的应用程序/ 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)
Run Code Online (Sandbox Code Playgroud)

完整的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})
Run Code Online (Sandbox Code Playgroud)

完整的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})
Run Code Online (Sandbox Code Playgroud)

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

assets/armeabi/mybinary
assets/x86_64/mybinary
... 
Run Code Online (Sandbox Code Playgroud)

为了在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");
Run Code Online (Sandbox Code Playgroud)

然后,应该使用正确的执行权限将二进制文件从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);
Run Code Online (Sandbox Code Playgroud)

就这样!

更新: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'
}
Run Code Online (Sandbox Code Playgroud)

  • 原来的gradle.build(作为整个项目)要复杂得多,所以我剪掉了不必要的部分.无论如何,我再次更新了答案,以更好地反映我的实际CMakeLists配置.查看3个CMakeLists.txt文件.但是,您是否在gradle构建文件中明确设置了"目标"? (2认同)
  • 我发布了一个示例代码:https://github.com/kangear/HelloJniExe/commit/af82fb0dd85a16a6856420f4c5cd55164b66e72f (2认同)