一.本文是主要寫GetFieldID,GetMethodID方法的使用
jclass clazz=(*env)->GetObjectClass(env,thiz);//其中的clazz就是Natvie class.
public class Native {<br />public String value="hello";<br />/**<br /> * this will return from JNI<br /> * @return<br /> */<br />public static int number=0;<br /> public static native String stringFromJNI();<br /> /**<br /> * pass the message to the JNI and<br /> * @param meg<br /> * @return JNI deal it message<br /> */<br /> public static native String getMessage(String meg);<br /> public native void getValue();</p><p> public void showMessage(){<br /> System.out.println("call the show Message");<br /> }<br />}
開始我在寫這個程式的時候一直報GetFileId ..No such "value".
找了好久才發現 我在Native.java中定義的 和getValue()也是用static
然後定義的value不是static.
在fid=(*env)->GetFieldID(env,clazz,"value","Ljava/lang/String;"); 報錯,是因為static方法中必須要用static的變數
所以我把getValue()方法的static方法去掉,下面是ok的代碼。
void Java_com_android_jni_Native_getValue(JNIEnv * env,jobject thiz){<br />jfieldID fid;<br />jfieldID fNumberId;<br />jstring jstr;<br />jmethodID mid;<br />const char * szTemp;<br />jclass clazz=(*env)->GetObjectClass(env,thiz);<br />print(clazz);<br />fid=(*env)->GetFieldID(env,clazz,"value","Ljava/lang/String;");<br />if(fid==NULL){<br />return;<br />}<br />jstr=(*env)->GetObjectField(env,thiz,fid);<br />szTemp=(*env)->GetStringUTFChars(env,jstr,NULL);<br />print(szTemp);<br />(*env)->ReleaseStringUTFChars(env,jstr,szTemp);<br />jstr=(*env)->NewStringUTF(env,"hello world");<br />if(jstr==NULL)<br />return;<br />(*env)->SetObjectField(env,thiz,fid,jstr);<br />//call the method showMessage<br />fNumberId=(*env)->GetStaticFieldID(env,clazz,"number","I");<br />if(fNumberId==NULL)<br />return;<br />jint num=(*env)->GetStaticIntField(env,clazz,fNumberId);<br />//print(num);<br />(*env)->SetStaticIntField(env,clazz,fNumberId,2);<br />mid=(*env)->GetMethodID(env,clazz,"showMessage","()V");<br />if(mid==NULL)<br />return ;<br />(*env)->CallVoidMethod(env,thiz,mid);<br />}
我本來想全部用static來解決就是
fid=(*env)->GetStaticFieldID(env,clazz,"value","Ljava/lang/String;");
不知道什麼原因,還是出現上面的錯誤。。後續來改。
今天試getMethodId();
mid=(*env)->GetMethodID(env,clazz,"showMessage","()V");//showMessage為Java中的方法,"()V"為該方法是return void的方法。
(*env)->CallVoidMethod(env,thiz,mid);
與GetMethodID相對應的是Call**Method().
對應static的屬性一定要用static的屬性。
fNumberId=(*env)->GetStaticFieldID(env,clazz,"number","I");
if(fNumberId==NULL)
return;
jint num=(*env)->GetStaticIntField(env,clazz,fNumberId);
//print(num);
(*env)->SetStaticIntField(env,clazz,fNumberId,2);
需要源碼的請留言給出mail的地址。