Android Studio CMake依赖第三方库
Posted mingfeng002
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Studio CMake依赖第三方库相关的知识,希望对你有一定的参考价值。
这里实现一个简单的功能在APP里调用libnative-lib.so里的add。libnative-lib.so去调用libthird.so里的third_add来实现
JniUtil
public class JniUtil { static { System.loadLibrary("native-lib"); System.loadLibrary("third"); } public static native int add(int x,int y); }
libnative.cpp
#include <jni.h> #include <string> #include "third.h" extern "C"{ JNIEXPORT jint JNICALL Java_com_test_ndkthirdso_JniUtil_add(JNIEnv *env, jclass type, jint x, jint y) { // TODO return third_add(x,y); } JNIEXPORT jstring JNICALL Java_com_test_ndkthirdso_MainActivity_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); } }
这里编译好一个自己写一个libthird.so库实现一个加法功能
third.h
#ifndef __H_THIRD #define __H_THIRD #ifdef __cplusplus extern "C" { #endif int third_add(int a, int b); #ifdef __cplusplus } #endif #endif // __H_THIRD
third.cpp
#include <jni.h> #include "third.h" int third_add(int a, int b){ return a+b; };
生成如下
项目工程结构如下:
CMakeLists.txt
cmake_minimum_required(VERSION 3.4.1) add_library(native-lib SHARED src/main/cpp/native-lib.cpp ) find_library(log-lib log ) #动态方式加载 third是libxxxx.so的xxxx部分 add_library(third SHARED IMPORTED) SET(third_path ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/${android_ABI}/libthird.so) #设置要连接的so的相对路径,${ANDROID_ABI}表示so文件的ABI类型的路径,这一步引入了动态加入编译的so set_target_properties(third PROPERTIES IMPORTED_LOCATION ${third_path}) MESSAGE(STATUS “src third so path= ${third_path}”) #配置加载native依赖 include_directories( ${ProjectRoot}/app/src/main/cpp/external/include ) target_link_libraries(native-lib third ${log-lib} )
gradle
apply plugin: \'com.android.application\'
android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "com.test.ndkthirdso"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your APK.
abiFilters \'armeabi\', \'armeabi-v7a\'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(\'proguard-android.txt\'), \'proguard-rules.pro\'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
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\'
})
compile \'com.android.support:appcompat-v7:26.+\'
compile \'com.android.support.constraint:constraint-layout:1.0.2\'
testCompile \'junit:junit:4.12\'
}
以上是关于Android Studio CMake依赖第三方库的主要内容,如果未能解决你的问题,请参考以下文章
使用 Android Studio 2.2 和 CMake 在 Android 中编译和使用依赖于 ABI 的可执行二进制文件
Android番外篇 Android Studio查看第三方库依赖树