个人博客地址:https://blog.yookingh.cn
该文章地址:https://blog.yookingh.cn/dev/200921-JNI_Study.html
目的:java代码调用C++代码
宏命令
javah
@Program $JDKPath$/bin/javah
@Arguments -v -jni -d $ModuleFileDir$/src/main/jni $FileClass$
@WorkingDirectory $SourcepathEntry$
ndk-build
@Program $Ndk路径$\ndk-build.cmd
@WorkingDirectory $ModuleFileDir$\src\main\
配置
app
下build.gradle
配置(无关配置使用...
代替)
...
def LIBRARY_NAME = "\"LIBRARY_KEYGEN\""//与稍后创建的工具类同名
...
android{
...
defaultConfig{
...
ndk {
moduleName LIBRARY_NAME
abiFilters "armeabi-v7a", "x86"//cpu的类型
}
}
buildTypes {
debug{
buildConfigField("String","LIBRARY_NAME",LIBRARY_NAME)
...
}
release {
buildConfigField("String","LIBRARY_NAME",LIBRARY_NAME)
...
}
}
sourceSets.main {
jni.srcDirs = ['libs']
}
}
local.properties
新增配置
# NDK路径
ndk.dir=D\:\\AndroidSDK\\ndk\\21.3.6528147
gradle.properties
新增配置
android.useDeprecatedNdk=true
具体步骤
1.创建调用JNI的工具类
package com.yooking.sodemo;
/**
* 通过JNI获取Key值
* Created by yooking on 2020/9/21.
* Copyright (c) 2020 yooking. All rights reserved.
*/
public class JniKeyUtils {
static {
System.loadLibrary(BuildConfig.LIBRARY_NAME);
}
public static native String getKeygen();
}
2.生成.h文件
右键单击JniKeyUtils
文件-NDK
(宏命令中的Group值)-javah
生成文件夹:app/src/main/jni
生成文件:com_yooking_sodemo_JniKeyUtils.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class com_yooking_sodemo_JniKeyUtils */
#ifndef _Included_com_yooking_sodemo_JniKeyUtils
#define _Included_com_yooking_sodemo_JniKeyUtils
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_yooking_sodemo_JniKeyUtils
* Method: getKeygen
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_yooking_sodemo_JniKeyUtils_getKeygen
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
3.创建.c文件
右键单击jni
文件夹-New
-C/C++ Source File
生成文件:JniKeyUtils.c
往文件中输入:
//
// Created by yooking on 2020/9/21.
// Copyright (c) 2020 yooking. All rights reserved.
//
#include "com_yooking_sodemo_JniKeyUtils.h"
JNIEXPORT jstring JNICALL Java_com_yooking_sodemo_JniKeyUtils_getKeygen
(JNIEnv * env, jclass object){
return (*env)->NewStringUTF(env,"取得密钥值");
}
4.创建.mk文件
- Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
#编译生成的文件的类库名——Build.gradle中的命名
LOCAL_MODULE := LIBRARY_KEYGEN
#要编译的c文件名称
LOCAL_SRC_FILES := JniKeyUtils.c
include $(BUILD_SHARED_LIBRARY)
- applicatiion.mk
#APP_ABI := all
#根据需要配置
APP_ABI := x86
5.生成.so文件
右键单击jni
文件夹-NDK
(宏命令中的Group值)-ndk-build
自动生成和jni
同级的obj
和libs
文件夹(obj
和libs
均可删除)
手动创建同级文件夹——jniLibs
文件夹
将libs
下的文件复制到jniLibs
中即可(或修改libs
文件名为jniLibs
)
6.运行测试
MainActivity.java
文件
package com.yooking.sodemo;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.tv_test)).setText(JniKeyUtils.getKeygen());
}
}
执行结果: