Using .so Files in Android Studio

I am new to Android. I have a basic hello-world code built-in function:

#include <string.h> #include <jni.h> #include <cassert> #include <string> #include <iostream> #include <fromhere.h> using namespace std; /* This is a trivial JNI example. * The string returned can be used by java code*/ extern "C"{ JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz ) { #if defined(__arm__) #if defined(__ARM_ARCH_7A__) #if defined(__ARM_NEON__) #if defined(__ARM_PCS_VFP) #define ABI "armeabi-v7a/NEON (hard-float)" #else #define ABI "armeabi-v7a/NEON" #endif #else #if defined(__ARM_PCS_VFP) #define ABI "armeabi-v7a (hard-float)" #else #define ABI "armeabi-v7a" #endif #endif #else #define ABI "armeabi" #endif #elif defined(__i386__) #define ABI "x86" #elif defined(__x86_64__) #define ABI "x86_64" #elif defined(__mips64) /* mips64el-* toolchain defines __mips__ too */ #define ABI "mips64" #elif defined(__mips__) #define ABI "mips" #elif defined(__aarch64__) #define ABI "arm64-v8a" #else #define ABI "unknown" #endif string s = returnit(); jstring retval = env->NewStringUTF(s.c_str()); return retval; } } 

Now, if I write fromhere.cpp as follows:

 #include <string> using namespace std; string returnit() { string s="Hello World"; return s; } 

I can enable fromhere.h by writing the fromhere.h file and declaring returnit therein and simply including the above file name in Android.mk LOCAL_SRC_FILES and "Hello World" will appear in the text view that I made from the java class.

But I want to compile these fromhere.cpp and fromhere.h as ready-made .so files created by ny ndk, and use the returnit () function. Can someone explain me step by step how to do this in Android Studio to be specific?

Please correct me if I said any nonsense.

+5
source share
1 answer

You said you were using Android Studio, but by default, Android Studio currently ignores your Makefiles and uses its own automatically created ones, without supporting native settings (for now).

If you deactivate built-in support and make calls to ndk-build yourself, adding something like this to your build.gradle:

 android { sourceSets.main { jniLibs.srcDir 'src/main/libs' //set libs as .so location instead of jniLibs jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk } } 

Here is the solution using Makefiles:

Android.mk

 LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES := fromhere.cpp LOCAL_MODULE := fromhere LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH) # useless here, but if you change the location of the .h for your lib, you'll have to set its absolute path here. include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) LOCAL_SRC_FILES := hello-world.cpp LOCAL_MODULE := hello-world LOCAL_SHARED_LIBRARIES := fromhere include $(BUILD_SHARED_LIBRARY) 
+1
source

All Articles