Jni初级

2020/12/14 23:46:23

Android Studio

1.配置javah,build-ndk,external tools
Crtl+Shift+S打开设置,Tools-->External Tools:
①:ndk-build
        programe:F:\code\Android\Android\Sdk\ndk\21.3.6528147\ndk-build.cmd
        arg:
workpath:$ProjectFileDir$\app\src\main
②:javah
        programe:$JDKPath$\bin\javah.exe
        arg:-jni $FileClass$
workpath:$SourcepathEntry$

2.local.properties:
ndk.dir=F\:\\code\\Android\\Android\\Sdk\\ndk\\21.3.6528147\

3.NDKTools:
public class NDKTools {
static {
System.loadLibrary("hello");
}
public static native String getStringFromNDK();
}

4.NDKTools.java右键javah

5.app/src/main新建jni,生成的.h文件拷贝进去

6.jni下新建hello.c
#include "com_lansea_ndkdemo_ndk_NDKTools.h"
JNIEXPORT jstring JNICALL Java_com_lansea_ndkdemo_ndk_NDKTools_getStringFromNDK
        (JNIEnv *env, jobject obj){
    return (*env)->NewStringUTF(env,"Hellow World!!!");
}

7.jni下新建Android.mk
include $(call all-makefiles-under,$(LOCAL_PATH))
LOCAL_PATH :=$(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE :=libhello
        LOCAL_SRC_FILES :=hello.c
        include $(BUILD_SHARED_LIBRARY)

8.jni右键ndk-build生成so文件

9.app:build.gradle:
defaultConfig:
ndk{
moduleName "libhello"
//abiFilters "armeabi", "armeabi-v7a", "x86"
abiFilters 'armeabi-v7a' ,'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
}
buildTypes:
externalNativeBuild {
ndkBuild {
path 'src/main/jni/Android.mk'
}
}
sourceSets.main {
jni.srcDirs = []
jniLibs.srcDirs = ['src/main/jniLibs']
}

10.Android.useDeprecatedNdk=true 

11.编译;结束