1、首先先創(chuàng)建一個(gè)普通的Android項(xiàng)目,

2、創(chuàng)建一個(gè)JniTest類,并且在類中創(chuàng)建native方法;

3、使用javaH生成.h文件,步驟如下:
打開(kāi)Terminal,進(jìn)入到工程的main目錄下 輸入一下命令

然后就會(huì)在java目錄下面生成com_yyz_test_jnidemo_JniTest.h
文件,然后在main目錄下面創(chuàng)建一個(gè)jni文件夾,把此文件拷貝到j(luò)ni目錄下面,可以重新命名JniTest.h(可以根據(jù)個(gè)人愛(ài)好命名),如圖

4、在jni目錄下面根據(jù)JniTest.h創(chuàng)建對(duì)應(yīng)的C文件,c文件中的內(nèi)容如下:
#include
#include
#include "JniTest.h"
JNIEXPORT jstring JNICALL Java_com_yyz_test_jnidemo_JniTest_getHello
(JNIEnv *env,jobject object){
return (*env)->NewStringUTF(env,"hello world From C");
}
5、創(chuàng)建Android.mk文件,內(nèi)容如下:
前兩項(xiàng)是固定寫(xiě)法,LOCAL_MODULE必須和JniTest中的sayJni保持一致,LOCAL_SRC_FILES 代表c文件的名稱 ,include $(BUILD_SHARED_LIBRARY)固定寫(xiě)法
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := sayJni
LOCAL_SRC_FILES := c_test.c
include $(BUILD_SHARED_LIBRARY)
6、在項(xiàng)目App根目錄下面創(chuàng)建CMakeLists.txt,文件內(nèi)容如下:
cmake_minimum_required(VERSION 3.4.1)
add_library(# Sets the name of the library.
# 設(shè)置so文件名稱.
sayJni
# Sets the library as a shared library.
SHARED
# 設(shè)置這個(gè)so文件為共享.
# Provides a relative path to your source file(s).
# 設(shè)置這個(gè)so文件為共享.
src/main/jni/c_test.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.
? ? # 制定目標(biāo)庫(kù).
? ? sayJni
# Links the target library to the log library
# included in the NDK.
? ? ${log-lib} )
7,在App中的build.gradle文件中defaultConfig添加
ndk{
moduleName"sayJni"
}
externalNativeBuild {
cmake {
cppFlags""
? ? ? ? //生成多個(gè)版本的so文件
? ? ? ? abiFilters'arm64-v8a','armeabi-v7a'
? ? }
}
在android下面添加
externalNativeBuild {
cmake {
path"CMakeLists.txt" //編譯后so文件的名字
? ? }
}
具體如下圖所示:
