1.AS中下载NDK与CMAKE(没用上,是另外一种方法的使用)
2.新建hello.java文件
public class hello {
static {
System.loadLibrary(“helloaa”); //把helloa库加载入内存
}
public static native String helloFromC(); //native方法
}
3.使用cmd命令 javac -encoding utf8 -h . hello.java(注意 点 后面有个空格)
环境为.java文件的同级目录使用此命令,会生成hello.java文件对应的.class文件和.h文件
4.在main目录下,即与java文件夹同级的目录中创建名为jni的文件夹
5.把生成的.h放入jni文件夹中(.class文件可以删除。。自测时 似乎不需要用)
6.在jni目录中创建hec.c文件 文件内容例如下文
#include <stdlib.h>
#include <stdio.h>
#include <jni.h>
//jstring
//Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
// jobject thiz )
//JNIEnv* env 是结构体JNINativeInterface 的二级指针
// JNIEnv 是结构体JNINativeInterface 的一级指针
// JNINativeInterface结构体中定义了大量的函数指针 这些函数指针在jni开发中很常用
// (*env)->
//jobject 调用本地函数的java对象 在这个例子中 就是MainActivity的实例
//c本地函数命名规则 Java_包名_类名_本地方法名
//jstring (*NewStringUTF)(JNIEnv*, const char*);
jstring Java_com_example_my_hello_helloFromC(JNIEnv* env,jobject thiz){
char* cstr = "CCCCCCCCCCCCCC!!!!!!";
return (*env)->NewStringUTF(env,cstr);
}
7.在jni文件夹中新建名为Android.mk文件,内容如下
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := helloaa //生成的库名,java中需要调用的库名
LOCAL_SRC_FILES := hec.c //需要调用的.c文件
include $(BUILD_SHARED_LIBRARY)
8.在工程的build.gradle文件中加入以下内容
sourceSets{
main(){
jniLibs.srcDirs=[‘src/main/libs’]
}
}
以下为build.gradle文件的全部内容
apply plugin: ‘com.android.application’
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.example.my"
minSdkVersion 14
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets{
main(){
jniLibs.srcDirs=['src/main/libs']
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
9.使用ndk-build命令 ,编译.c文件,使之生成对应的.so文件
注意使用此命令时 需要在jni文件目录下使用例如:
ts@ts-OptiPlex-7070:~/AndroidStudioProjects/My2/app/src/main/jni$ ndk-build
10.完成调用!