记录几个Android JNI的使用技巧

Jni 调用java方法

// 1、先找到类。下面是两种找到类的方式
jclass cls1= env->FindClass("com/dv/MyJni");
jclass cls2 = env->GetObjectClass(people);

// 2、再找到方法的id。下面是寻找people类里面的 “void say()” 方法
jmethodID methodId = env->GetMethodID(cls, "say", "()V");

// 3、让对象调用say方法
env->CallVoidMethod(people, methodId);
jclass localClass = env->FindClass("com/dv/MyJni");
jmethodID methodID = env->GetStaticMethodID(localClass,"onMeasureResult", "(FFF)V");
env->CallStaticVoidMethod(localClass,methodID,1.2f,1.1f,1.1f);

关于JNI方法签名规则

JNI识别Java方法 : JNI依靠函数名 和 方法签名 识别方法, 函数名是不能唯一识别一个方法的, 因为方法可以重载, 类型签名代表了 参数 和 返回值;
-- 签名规则 : (参数1类型签名参数2类型签名参数3类型签名参数N类型签名...)返回值类型签名, 注意参数列表中没有任何间隔;

Java类型 与 类型签名对照表 : 注意 boolean 与 long 不是大写首字母, 分别是 Z 与 J, 类是L全限定类名, 数组是[元素类型签名;
-- 类的签名规则 :L + 全限定名 + ;三部分, 全限定类名以 / 分割;
Java类型 类型签名
byte B
char C
short S
int I
long J
float F
double D
L全限定类名
数组 [元素类型签名

在C++的子线程里调用java方法

在jni接口里调用

JavaVM *g_jvm = NULL;
jobject g_obj = NULL;
//保存全局JVM以便在子线程中使用
env->GetJavaVM(&g_jvm);
//不能直接赋值(g_obj = obj)
g_obj = env->NewGlobalRef(obj);

在子线程里调用

//Attach主线程
if(g_jvm->AttachCurrentThread(&env, NULL)  !=  JNI_OK)
{
    return;
}
jclass cls = env->GetObjectClass(g_obj);
jmethodID method = env->GetMethodID(cls, "hello", "()V");
env->CallVoidMethod(g_obj, method);

28 评论

  1. Hi superb blog! Does running a blog similar to this require a massive amount work?

    I have very little expertise in coding however I was hoping to start my
    own blog in the near future. Anyhow, if you have any
    ideas or tips for new blog owners please share. I understand this is off
    topic but I just wanted to ask. Thanks a lot!

  2. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your site?
    My blog is in the exact same area of interest as yours and my visitors would truly benefit from a lot
    of the information you provide here. Please let me know if this ok
    with you. Regards!

  3. I’m extremely impressed with your writing skills as well as with the layout on your blog.
    Is this a paid theme or did you customize it yourself?
    Either way keep up the nice quality writing, it is rare to see a great
    blog like this one these days.

  4. Hello! I’m at work surfing around your blog from my new apple iphone!
    Just wanted to say I love reading your blog and look forward to all your posts!
    Keep up the fantastic work!

  5. Excellent way of explaining, and pleasant paragraph to take facts concerning
    my presentation subject matter, which i am going to convey in institution of higher education.

  6. Have you ever considered writing an ebook or
    guest authoring on other websites? I have a
    blog centered on the same information you discuss and would love to have you share some stories/information.
    I know my audience would appreciate your work. If you are even remotely interested,
    feel free to send me an email.

发表评论

电子邮件地址不会被公开。