在Android Studio中使用.so文件

Rag*_*lli 5 android shared-libraries android-ndk android-studio

我是Android新手.我有一个基本的hello-world本机代码函数,如下所示:

    #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;
    }
    }
Run Code Online (Sandbox Code Playgroud)

现在如果我从wherehere.cpp写如下:

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

我可以通过编写fromhere.h文件并在其中声明returnit来包含fromhere.h,并在Android.mk的LOCAL_SRC_FILES中包含上述文件的名称,并且在我从java类创建的文本视图中出现"Hello World".

但是我希望将这些fromhere.cpp和fromhere.h编译为prebuilt .so文件,构建ny ndk并使用returnit()函数.有人可以一步一步地向我解释如何在Android Studio中具体做到这一点吗?

如果我说废话,请纠正我.

ph0*_*h0b 1

您说您正在使用 Android Studio,但默认情况下 Android Studio 目前会忽略您的 Makefile 并使用它自己的自动生成的文件,不支持本机依赖项(目前)。

如果您停用内置支持并自己调用 ndk-build,请在 build.gradle 中放入类似以下内容:

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

这是使用 Makefile 的解决方案:

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)
Run Code Online (Sandbox Code Playgroud)