Android NDK(JNI)详解教程三 Java调用JNI方
2023-03-01 本文已影响0人
Kael_Zhang的安卓笔记
JAVA调用
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_sample_projectname_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
public class MainActivity extends AppCompatActivity {
// Used to load the 'myndk' library on application startup.
static {
System.loadLibrary("projectname");
}
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Example of a call to a native method
binding.tvjni.setText(stringFromJNI());
}
/**
* A native method that is implemented by the 'myndk' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
编译配置
android {
defaultConfig {
externalNativeBuild {
cmake {
// 支持 c++11,配置内容仅举例,具体以实际项目需求为准
cppFlags '-std=c++11'
// 需要运行的 CPU 类型,配置内容仅举例,具体以实际项目需求为准
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
}
}
}
// cmake 配置,以下是默认配置,配置内容仅举例,具体以实际项目需求为准
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.18.1'
}
}
}