Here to implement a simple function in the app call libnative-lib.so Add. Libnative-lib.so to call the Third_add in libthird.so to realize
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 jnicalljava_com_test_ndkthirdso_jniutil_add (jnienv*env, Jclass type, Jint x, Jint y) { //TODO returnthird_add (x, y);} Jniexport jstring Jnicalljava_com_test_ndkthirdso_mainactivity_stringfromjni (jnienv*Env, Jobject/* This*/) {std::stringHello ="Hello from C + +"; returnEnv->Newstringutf (Hello.c_str ());}}
Here compile good one to write a libthird.so library to implement an addition function
Third.h
#ifndef __h_third #define __h_third#ifdef __cplusplusextern"C" { #endifint third_add (intint b), #ifdef __cplusplus}#endif #endif // __h_third
Third.cpp
#include <jni.h>"third.h"int third_add (intint b) {return a +b;};
Generate the following
Project engineering structure is as follows:
CMakeLists.txt
3.4. 1 ) add_library (native-lib SHARED src/main/cpp/native-lib.cpp) find_library (log -lib log) #动态方式加载 Third is the XXXX part of Libxxxx.so add_library (third SHARED imported) SET (Third_path ${cmake_current_ Source_dir}/src/main/jnilibs/${android_abi}/libthird.so) #设置要连接的so的相对路径, ${android_abi} represents the path to the ABI type of the so file, This step introduces the dynamic addition of the compiled Soset_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 buildtoolsversion "26.0.0" Defaultconfig { ApplicationID "Com.test.ndkthirdso" Minsdkversion targetsdkversion versioncode 1 Versionname "1.0" Testinstrumentationrunner "Android.support.test.runner.AndroidJUnitRunner" EXTERNALNATIVEB uild {cmake {cppflags "-frtti-fexceptions"}} NDK {//S Pecifies 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 '}} Externalna Tivebuild {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 ', M Odule: ' Support-annotations '}) Compile ' com.android.support:appcompat-v7:26.+ ' compile ' com.android.support.cons traint:constraint-layout:1.0.2 ' Testcompile ' junit:junit:4.12 '}
Android Studio CMake relies on third-party libraries