赞
踩
新建能编译APK的工程,工程中添加相关ndk目录
添加完成后,工程目录自动更新,build.gradle导入了so编译器
修改build.gradle中添加相关gcc编译器如下
externalNativeBuild {
cmake {
abiFilters 'arm64-v8a', 'armeabi-v7a'
cppFlags ''
}
}
新建JniTest.java文件,相关代码如下
package com.example.test;
import android.util.Log;
public class JniTest {
private static final String TAG="JniTest";
static {
try {
System.loadLibrary("test");
} catch (Exception e){
Log.e(TAG,"load jni failed " + e);
}
}
public native int add(int x, int y);
public void soCallBackTest(String from) {
Log.d(TAG,"soCallBackTest " + from);
}
}
注意一点 这个地方名字一样
执行通过javah -jni com.example.test.JniTest生成com_example_test_JniTest.h
将其剪切到 E:\Code\Test\app\src\main\cpp\
编写test.cpp如下
#include "com_example_test_JniTest.h"
#include <android/log.h>
#define TAG "Jni"
JNIEXPORT jint JNICALL Java_com_example_test_JniTest_add
(JNIEnv *env, jobject obj, jint num1, jint num2){
__android_log_print(ANDROID_LOG_DEBUG, TAG,"%s jin1 = %d, jin2 =%d", __FUNCTION__ ,num1, num2);
int result = num1 + num2;
/*from c to java*/
jclass jclazz = env ->FindClass("com/example/test/JniTest");
jmethodID jmethodIds = env ->GetMethodID(jclazz, "soCallBackTest", "(Ljava/lang/String;)V");
jobject jobject1 = env->AllocObject(jclazz);
jstring jst = env->NewStringUTF("I am Android!");
env ->CallVoidMethod(jobject1, jmethodIds, jst);
return result;
}
编译APK后进行安装调试
CMake官方网站:https://cmake.org/getting-started/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。