NDK介绍

NDK与Java工程的区别

第一个NDK工程

so中常用的Log输出

NDK多线程简介

JNI_OnLoad

JavaVM

JNIEnv

so相关的几个概念

so函数注册

so之间的相互调用

so路径的动态获取

通过jni创建Java对象

//1、找类
//2、得到方法id
//3、创建对象
jclass clazz = env->FindClass("com/xiaojianbang/ndk/NDKDemo");
jmethodID methodID = env->GetMethodID(clazz,"<init>","()V");
jobject ReflectDemoOjb = env->NewObject(clazz,methodID);
LOGD("ReflectDemoObj %p",ReflectDemoObj);

通过jni访问Java属性

jmethodID methodID = env->GetMethodID(clazz,"<init>","()V");
//获取静态字段
//1、找到类
jclass clazz = env->FindClass("com/xiaojianbang/ndk/NDKDemo");
//2、获取字段id
jfieldID privateStaticStringField = env->GetStaticFieldID(clazz,"privateStaticStringField","Ljava/lang/string;");
//3、获取字段内容
jstring privateStaticString = static_cast<jstring>(env->GetStaticObjectField(clazz,privateStaticStringField));
//4、将jstring转换为cstring
const char* privatestr = env->GetStringUTFChars(privateStaticString,nullptr);
//5、释放
env->ReleaseStringUTFChars(privateStaticString,privatestr);
//获取对象字段
//1、找到类
jclss clazz = env->FIndClass("com/xiaojianbang/ndk/NDKDemo");
jmethodID methodID = env->GetMethodID(clazz,"<init>","()V");
jobject ReflectDemoOjb = env->NewObject(clazz,methodID);
//2、获取字段id
jfieldID publicStringField = env->GetFieldID(ReflectDmmoObj,"publicStringField","L/java/lang/String");
//3、获取字段内容
jstring publicString = static_cast<jstring>(env->GetObjectField(clazz,publisStringField));
//4、将jstring转换为cstring
const char* publicstr = env->GetStringUTFChars(publicString,nullptr);
//5、释放
env->ReleaseStringUTFChars(publicString,publicstr);
//设置字段
//1、找到类
jcalss clazz = FindClass("com/xiaojianbang/ndk/NDKDemo");
//2、获取字段id
jfieldID publicStringField = env->GetFieldID(clazz,"publicStringField","L/java/lang/String");
env->SetObjectField(clazz,publicStringField,env->NewStringUTF("xiaojianbang"));

通过jni访问Java数组

通过jni访问Java方法

通过jni访问Java父类方法

extern "C"
JNIEXPORT void JNIDCALL
Java_com_comxiaojianbang_ndkdemo_MainActivity_onCreate(JNIEnv *env, jobject thiz,jobject saved_instance_state){
jclass AppCompatActivityClazz = env->FindClass("androidx/appcompat/app/AppCompatActivity");
jmethodid onCreateID = env->GetMethodID(AppCompatActivityClazz,"onCreate","(Landroid/os/Bundle;)V");
env->CallNonvirtualVoidMethod(thiz,AppCompatActivityCalzz,onCreateID,saved_instance_state);
}

内存管理

子线程获取Java类

jclass MainActivityClazz = env->FindClass("com/xiaojianbang/ndkdemo/MainActivity");
jclass classClazz = env->FindClass("java/lang/Class");
jmethodID getClassLoaderID = env->GetMethodID(classClazz,"getClassLoader","()Ljava/lang/ClassLoader;");
jobject tempClassLoaderObj = env->CallObjectMethod(MainActivityClazz,getClassLoaderID);
jobject ClassLoaderObj = env->NewGlobal(tempClassLoaderObj);

init与initarray