1.App Build Gradle configuration
In Android’s DEFAULTCONFIG domain for the following configuration
Externalnativebuild {
cmake {
cppflags "" ""
// Generate multiple versions of so files
Abifilters 'Armeabi-V7a'
}
}
In the Android domain, the following configuration
Externalnativebuild {
cmake {
PATH "SRC/main/cpp/cmakelists.txt" // Set the C source code position to be written, and the name of the SO file after compilation
version "3.10.2"
}
}
2.cmakelist.txt configuration
cmake_minimum_required(VERSION 3.4.1)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native_src.c)
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 )
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
3.c file implementation
#include <jni.h>
#include <assert.h>
#include <string.h>
#include <pthread.h>
#include <nistd.h>
#include <Android/log.h>
#Define tag "hello"
#Define logv (...) __android_log_print (android_log_verbose, tag, __va_args__)
#Define logd (...) __android_log_print (android_log_debug, tag, __va_args__)
#Define logi (...) __android_log_print (android_log_info, tag, __va_args__)
#Define logw (...) __ANDROID_LOG_PRINT (Android_log_warn, Tag, __va_ARGS__)
#Define Loge (...) __ANDROID_LOG_PRINT (Android_log_error, Tag, __va_ARGS__)
#Ifndef Nelem
#Define NELEM (a) (SIZEOF (a)/SIZEOF (a [0]))
#Endif
static javavm* g_jvm;
// jstring jnicall
// java_com_example_myApplication_MAINACTITY_STRINGFROMJNI (
// jnienv *ENV,
// jobrz/ * this */) {) {
// char* hello = "Hello from c ++";
// Return (*ENV)-> Newstringutf (ENV, Hello);
//}
Jstring StringFromjni
{{
// jnienv *ENV = NULL;
// // g_jvm-> AttachcurrentthRead (& ENV, NULL); // G_JVM is Javavm pointer
// (*g_jvm)-> Getenv (g_jvm, (void **) & env, jni_version_1_4);
Return (*ENV)-> Newstringutf (ENV, "Hello from JNI!"););
}
Static JNInaticMethod Methods [] = {
{"stringfromjni", "() ljava/lang/string;", (void*) stringfromjni},
};
JNIEXPORT JINT JNI_ONLOAD (javavm *vm, void *reserved)
{{
Jnienv* ENV = NULL;
g_jvm = vm;
jclass class;
Static Const Char *ClasspathName = "COM/EXAMPLE/Debugnative/MainActivity";
if ((*vm)-> Getenv (vm, (void **) & env, jni_version_1_4)! = jni_ok) {
Return -1;
}
assert (env! = null);
Clazz = (*ENV)-> FindClass (ENV, ClassPathName);
Logv ("Clazz = %D", Clazz);
If (*ENV)-> Registernatives (ENV, Clazz, Methods, Nelem (Methods)) <0) {{
Logv ("registernatives failed");
Return -1;
}
Logv ("JNI_ONLOAD Success");
Return jni_version_1_4;
}