1.生成so库
2.把生成的so库复制到项目libs目录文件夹
3.修改项目build.gradle文件
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.administrator.aslibtest1"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
//如果需要指定开发平台 如:
/*ndk {
abiFilters "armeabi","x86"
}*/
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
// 引入第三方库,在app.gralde中的android目录下
sourceSets.main {
jniLibs.srcDirs = ['libs']
jni.srcDirs = []
}
}
4.修改CMakeLists.txt
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
find_library( # Sets the name of the path variable.
log-lib
log )
#设置so库路径
set(my_lib_path ${CMAKE_SOURCE_DIR}/libs)
#讲第三方库作为动态库引用
add_library( native-lib
SHARED
IMPORTED )
#指名第三方库的绝对路径
set_target_properties( native-lib
PROPERTIES IMPORTED_LOCATION
${my_lib_path}/${ANDROID_ABI}/libnative-lib.so )
add_library( # Sets the name of the library.
libTest
SHARED
src/main/cpp/native-lib.c )
target_link_libraries( # Specifies the target library.
libTest
native-lib
${log-lib} )
5.添加头文件
6.触发JNI调用
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
System.loadLibrary("libTest");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(""+stringFromJNI(99,66));//165
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native int stringFromJNI(int a,int b);
}