我正在使用android gradle实验插件来构建一个带有一些本机代码的应用程序模块。这个原生代码使用了一个带有预构建 .so 文件的库,我通过 android 库模块将其捆绑到一个 .aar 文件中。.aar 文件构建良好,但如何将应用模块中的本机代码模块链接到 .aar 模块中的预构建 .so 文件?gradle 实验文档没有提到这种情况。
另外,如果可能的话,我想将包含文件打包到 .aar 文件中(尽管它们不应该与最终应用程序打包(。
在/prebuiltlib 中:
build.gradle
-src/
--main/
---jniLibs/
----libfoo.so
以下是 gradle 文件:
/prebuiltlib/build.gradle
apply plugin: "com.android.model.library"
model {
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
minSdkVersion.apiLevel = 21
targetSdkVersion.apiLevel = 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles.add(file("proguard-rules.pro"))
}
}
}
}
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:25.3.1"
}
这是/app/build.gradle,请注意我不确定要放什么的???:
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.model.application'
model {
repositories {
libs(PrebuiltLibraries) {
// ??? is this right, and does this go into app/build.gradle or mylib/build.gradle?
foo {
binaries.withType(SharedLibraryBinary) {
sharedLibraryFile = file('???/libfoo.so')
}
}
}
}
android {
compileSdkVersion = 25
buildToolsVersion = '25.0.3'
defaultConfig {
applicationId = 'com.jeremy.stackoverflow.sample'
minSdkVersion.apiLevel = 21
targetSdkVersion.apiLevel = 21
versionCode = 1
versionName = '1.0'
}
ndk {
platformVersion = 21
moduleName = 'native-activity'
toolchain = 'gcc'
toolchainVersion = '4.9'
stl = 'gnustl_shared'
abiFilters.add('armeabi-v7a')
ldLibs.addAll(['log',
'android',
'EGL',
'GLESv2'
])
// ??? How do I add include paths from the .aar module?
cppFlags.add('-I' + file('???/include'))
cppFlags.addAll(['-std=c++11', '-fexceptions'])
}
sources {
main {
jni {
dependencies {
// ??? Is this right?
library 'foo' linkage 'shared'
}
}
jniLibs {
source {
// ??? Do I need one of these for the libs in the .aar?
srcDir file('???/jniLibs')
}
dependencies {
// ??? Is this right?
library 'foo'
}
}
}
}
buildTypes {
release {
minifyEnabled = false
proguardFiles.add(file('proguard-rules.pro'))
}
}
}
}
dependencies {
println rootProject.getName()
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.3.1'
compile project(':prebuiltlib')
}
从 Android Gradle 插件 4.0 开始,C/C++依赖项可以从 build.gradle 文件中链接的 AAR 导入。Gradle 会自动向原生构建系统提供这些库和标头,但您的构建系统必须配置为使用导入的库和标头。
在 gradle 4.0 中:将以下内容添加到项目的 gradle.properties 文件中:
android.enablePrefab=true
在 gradle 4.1 中:将以下内容添加到模块 build.gradle 文件的 android 块中:
buildFeatures {
prefab true
}
,如果应用程序定义了 libapp.so 并使用 cURL,则 CMakeLists.txt 应包括以下内容:
add_library(app SHARED app.cpp)
# Add these two lines.
find_package(curl REQUIRED CONFIG)
target_link_libraries(app curl::curl)
app.cpp现在可以 #include"curl/curl.h",libapp.so 构建时会自动链接到 libcurl.so,libcurl.so 将包含在APK中。
来源: https://developer.android.com/studio/build/native-dependencies