Android NDK之----- C呼叫Java [GetMethodID方法的使用]
阿新 • • 發佈:2019-02-16
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 記憶體不足