其实第一弹已经实现了,不过第一弹重点是为了引入外部so库文件,导致写得有些杂乱,这里转专门开一弹写Cmake引入的方法
- 创建Android Studio项目,省略
- MainActivity内容,于第一弹基本相同
package org.eu.uiai.jnilearn;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static {
System.loadLibrary("my_lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView ss=findViewById(R.id.show_string);
TextView st=findViewById(R.id.show_text);
JniApi jApi=new JniApi();
int a=9,b=10;
ss.setText(jApi.getString(1));
st.setText(a+"+"+b+"="+jApi.getSum(a,b));
}
}
- 写API接口类JniApi
package org.eu.uiai.jnilearn;
public class JniApi {
public native String getString(int id);
public native int getSum(int a,int b);
}
- 通过指令生产jni头文件
javac ./app/src/main/java/org/eu/uiai/jnilearn/JniApi.java -h ./app/src/main/jni
- 生成的头文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class org_eu_uiai_jnilearn_JniApi */
#ifndef _Included_org_eu_uiai_jnilearn_JniApi
#define _Included_org_eu_uiai_jnilearn_JniApi
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_eu_uiai_jnilearn_JniApi
* Method: getString
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_eu_uiai_jnilearn_JniApi_getString
(JNIEnv *, jobject, jint);
/*
* Class: org_eu_uiai_jnilearn_JniApi
* Method: getSum
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_org_eu_uiai_jnilearn_JniApi_getSum
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
- 根据头文件写Cpp的实现
#include "org_eu_uiai_jnilearn_JniApi.h"
JNIEXPORT jstring JNICALL Java_org_eu_uiai_jnilearn_JniApi_getString
(JNIEnv *env, jobject, jint){
return env->NewStringUTF("你好世界!");
}
JNIEXPORT jint JNICALL Java_org_eu_uiai_jnilearn_JniApi_getSum
(JNIEnv *, jobject, jint a, jint b){
return a+b;
}
- 修改build.gradle文件
......
android {
......
defaultConfig {
......
//{添加内容开始
externalNativeBuild {
cmake {
arguments "-DANDROID_STL=c++_shared"
}
}
//添加内容结束}
......
}
//{添加内容开始
externalNativeBuild {
cmake {
path "src/main/jni/CMakeLists.txt"
}
}
//添加内容结束}
......
}
dependencies {
......
}
- CMakeList.txt文件内容
add_library(my_lib SHARED my_lib.cpp)
评论区