The native code native.c
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_com_lab5_oli_myapplication_MainActivity_helloWorld(JNIEnv* env,jobject obj)
{
return (*env)->NewStringUTF(env,"Hello world");
}
Android.mk file
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE:=ocrex
LOCAL_SRC_FILES:=ndkTest.c
include $(BUILD_SHARED_LIBRARY)
Application.mk file
APP_ABI := all
code in MainActivity
public native String helloWorld();
static{
System.loadLibrary("ocrex");
}
The method is recognised to be declared in the native code(note on side bar)
First if you are using android studio 2.2 and above use Cmake because Android Studio's default build tool for native libraries is CMake. But if you need the ndk-build android studio still supports the ndk-build.
1) Add JNIEXPOT and JNICALL into the native method and make sure the com_lab5_oli_myapplication is the package name of the MainActivity class.
#include <string.h>
#include <stdio.h>
#include <jni.h>
JNIEXPORT jstring JNICALL Java_com_lab5_oli_myapplication_MainActivity_helloWorld(JNIEnv* env,jobject obj)
{
return (*env)->NewStringUTF(env,"Hello world");
}
2) And in the Android.mk file change the source name your c++ name is native.c but in the Android.mk file you used ndkTest.c file name.
LOCAL_SRC_FILES:=ndkTest.c
//change it to
LOCAL_SRC_FILES:=native.c
Finally you have to link the gradle into native library. 1) If you have android studio 2.2 and above right click on the app and there is Link c++ project with gradle. If you are using ndk-build then choose the Android.mk file if you are using Cmake build choose the insert the address of the CmakeLists. 2) You can also manually configure gradle to include the native library.You need to add the externalNativeBuild block to your module-level build.gradle file and configure it with either the cmake or ndkBuild block: If you are using cmake
externalNativeBuild {
// Encapsulates your CMake build configurations.
cmake {
// Provides a relative path to your CMake build script.
path "CMakeLists.txt"
}
}
And if you are using ndk-build
externalNativeBuild {
// Encapsulates your CMake build configurations.
ndkBuild {
// Provides a relative path to your to the Android.mk build script.
path "Android.mk"
}
}
For detail information about cmake and ndk in android use this and this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With