我们在java的路径下,通过右键->new->Folder->JniFolder 建立一个JNI文件,然后把这个头文件拖入到jni目录下。而之前那个.class文件就可以删除掉了
接下来我们在jni下新建一个cpp文件 Mp3Encoder,将刚刚生成文件的内容全部复制到这个文件下面,并且实现对应的方法,这里就是做一个日志打印.:
//
// Created by msn on 2019/11/17.
//
#include <jni.h>
#include <android/log.h>
#define LOG_TAG “Mp3Encoder”
#ifndef _Included_com_rikkatheworld_mp3encoder_studio_Mp3Encoder
#define _Included_com_rikkatheworld_mp3encoder_studio_Mp3Encoder
//宏定义 一个日志打印
#define LOGI(…) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, VA_ARGS)
#ifdef __cplusplus
extern “C” {
#endif
JNIEXPORT void JNICALL Java_com_rikkatheworld_mp3encoder_studio_Mp3Encoder_encoder
(JNIEnv *, jobject) {
//这里就做一个打印日志
LOGI(“encoder encode”);
}
#ifdef __cplusplus
}
#endif
#endif
接着在 app build.gradle下加入:
android {
defaultConfig {
…
externalNativeBuild {
cmake {
//设置C++标准为默认
cppFlags “”
}
}
ndk {
//ndk模块名称
moduleName “mp3_encoder”
//声明log
ldLibs “log”
}
}
externalNativeBuild {
cmake {
//指定CMake文件路径
path “CMakeLists.txt”
}
}
}
接着我们在 app下面创建 CMakeLists.txt
,(以前是使用Android.mk,这个相当于代替它的)
For more information about using CMake with Android Studio, read the
documentation: https://d.android.com/studio/projects/add-native-code.html
Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
Creates and names a library, sets it as either STATIC
or SHARED, and provides the relative paths to its source code.
You can define multiple libraries, and CMake builds them for you.
Gradle automatically packages shared libraries with your APK.
add_library( # 输入ndk使用的名称
mp3_encoder
Sets the library as a shared library.
SHARED
输入你的cpp的路径名.
src/main/jni/Mp3Encoder.cpp )