Activity代码:
package com.test.jniclass;
import android.app.Activity;
import android.os.Bundle;
public class AndroidJniClassDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
executeMethod();
}
private void show(){
System.out.println("AndroidJniClassDemo show function");
}
private int intShow(){
System.out.println("AndroidJniClassDemo intShow function");
return 1;
}
private native void executeMethod();
static{
System.loadLibrary("AndroidJniDemo");
}.c文件代码:
#include<jni.h>
#include<stdio.h>
#include<android/log.h>
JNIEXPORT void JNICALL Java_com_test_jniclass_AndroidJniClassDemo_executeMethod (JNIEnv *env, jobject obj)
{
jclass clazz = (*env)->GetObjectClass(env,obj); //通过类的对象
jmethodID mid = (*env)->GetMethodID(env,clazz,"show","()V");//查找java中的show方法的ID,最后的签名符号为void类型
if(mid == NULL)
{
__android_log_print(ANDROID_LOG_INFO,"HGY", "method show ID not found");
return; //如果方法ID没有找到
}
jmethodID intshowID = (*env)->GetMethodID(env,clazz,"intShow","()I");
if(intshowID == NULL)
{
__android_log_print(ANDROID_LOG_INFO,"HGY", "method intShow ID not found");
return; //如果方法ID没有找到
}
__android_log_print(ANDROID_LOG_INFO,"HGY", "will execute show function");
(*env)->CallVoidMethod(env,obj,mid); //执行show方法
__android_log_print(ANDROID_LOG_INFO,"HGY", "will execute intShow function");
(*env)->CallIntMethod(env,obj,intshowID); //执行show方法
}
首先说下有关签名sig相关的比如 "Ljava/lang/String;"
1. jmethodID GetMethodID(JNIEnv *env, jclass clazz,const char *name, const char *sig); 获取一个Java方法的ID
这个函数将返回非静态类或接口实例方法的方法 ID。这个方法可以是某个clazz 的超类中定义,也可从clazz 继承,最后一个参数为签名,最后两个参数是const char*类型,是utf8类型。需要注意的是执行GetMethodID()函数将导致未初始化的类初始化,如果要获得构造函数的方法ID,使用 <init> 作为方法名,同时将 void (V) 作为返回类型,如果找不到指定的ID将返回NULL,同时异常可能有:
(1 NoSuchMethodError 找不到指定的Java方法。
(2 ExceptionInInitializerError 如果由于异常而导致类初始化程序失败
(3 OutOfMemoryError 内存不足
本文介绍了在Android NDK中如何使用C语言调用Java方法,特别是GetMethodID函数的使用。该函数用于获取非静态类或接口的方法ID,通过类名、方法名和签名字符串。如果类未初始化,执行此函数会触发初始化,如果找不到方法则抛出异常,如NoSuchMethodError、ExceptionInInitializerError或OutOfMemoryError。文章还提示了编码签名的细节,并预告下篇将继续探讨该主题。
732

被折叠的 条评论
为什么被折叠?



