不BB,开怼。
环境: Android studio 3.2 Cmake
app目录下 添加一个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)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # so文件调用名称.
mycall
# Sets the library as a shared library.
SHARED
# C文件路劲.
src/main/cpp/mycall.c)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log)
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries(
mycall
${log-lib})
build.gradle 添加
defaultConfig {
applicationId "com.example.administrator.ndkbuilddemo"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
//生成多个版本的so文件
abiFilters 'arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64'
}
}
}
android {
......
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
......
}
java 调用 C
native 方法 然后在cpp/c 文件中添加对应的方法 然后编译即可。
或者对着方法名
生成一哈。
就会在C/CPP 文件内 生成对应的方法
然后就开始搞事情就可以了。。
C调用JAVA方法
// 反射java类的字节码 jclass (*FindClass)(JNIEnv*, const char* = 包名+类名);
jclass clz=(*env)->FindClass(env,"com/example/administrator/ndkdemo3/JNI");
//调取方法 jmethodID (*GetMethodID)(JNIEnv*, jclass=类, const char* = 方法名 , const char* =签名 );
//关于签名 需要生成class 后 到class文件夹下 执行 javap -s 文件名 编译得到方法签名列表
jmethodID mtd=(*env)->GetMethodID(env,clz,"showText","(II)V");
//得到类对象jobject (*AllocObject)(JNIEnv*, jclass = 上面的字节码 );
jobject jb=(*env)->AllocObject(env,clz);
// 执行方法 void (*CallVoidMethod)(JNIEnv*, jobject=类对象, jmethodID=方法 , ... = 参数xN);
(*env)->CallVoidMethod(env,jb,mtd,77,66);
签名需要说一下:
方法签名需要到编译后的class文件下 执行 javap -s 文件.class
全部完事后 执行 得到C调java的返回结果
jni.h的文件 有很多示例可以参考。
比如说:酱紫的。
剩下自由发挥。。