android中使用jni,ndk的C语言回调方法
android中使用jni,ndk的C语言回调方法
(2010-10-23 14:06:59)
不说太罗嗦了,回调分为Java代码和C语言代码两部分,我举的例子简单而且是通过调试可以运行的.
Java代码:
//==================================================================== packagecom.example.hellojni;
importandroid.app.Activity;
importandroid.util.Log;
importandroid.widget.TextView;
importandroid.os.Bundle;publicclassHelloJniextendsActivity
{
publicStringmJniMsg;
publicHelloJni(){}
@Override
publicvoidonCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);//System.loadLibrary("hello-jni");
TextViewtv=newTextView(this);
tv.setText("Eagle,morning!");
setContentView(tv);
doCLanguageWork();
}public void myCallbackFunc(String nMsg)
{
Log.v("EagleTag","backmessage:"+nMsg);
}
publicnative String doCLanguageWork();static
{
System.loadLibrary("hello-jni");
}
}C语言代码部分:
//====================================================================
#include<string.h>
#include<jni.h>JNIEXPORTjstring JNICALL
jobjectgJniObj;
jclassgJniClass;
jmethodID gJinMethod;voidGetInstance(JNIEnv*env,jclassobj_class);
void DisplayCallBack(JNIEnv* env);JNIEXPORTjstring JNICALL
Java_com_example_hellojni_HelloJni_doCLanguageWork(JNIEnv*env,jobjectobj)
{
chartChar[256];
gJniClass=0;
gJinMethod=0;
gJniClass=(*env)->FindClass(env,"com/example/hellojni/HelloJni");
if(gJniClass==0||gJniClass==NULL)
return(*env)->NewStringUTF(env,"-1");
GetInstance(env,gJniClass);gJinMethod=(*env)->GetMethodID(env,gJniClass,"myCallbackFunc","(Ljava/lang/String;)V");
if(gJinMethod==0||gJinMethod==NULL)
return(*env)->NewStringUTF(env,"-2");
strcpy(tChar,"PROG:10");
(*env)->CallVoidMethod(env,gJniObj,gJinMethod,(*env)->NewStringUTF(env,tChar));
DisplayCallBack(env);
return(*env)->NewStringUTF(env,"Eagleisreallygreat!......");
}voidGetInstance(JNIEnv* env, jclass obj_class)
{
jmethodIDconstruction_id=(*env)->GetMethodID(env,obj_class,"<init>","()V");
gJniObj=(*env)->NewObject(env,obj_class,construction_id);
}voidDisplayCallBack(JNIEnv* env)
{
chartChars[256];
strcpy(tChars,"DEBUG:Hello,Eagle");
(*env)->CallVoidMethod(env,gJniObj,gJinMethod,(*env)->NewStringUTF(env,tChars));
}
怎么样?不是很难吧?具体能不能理解,就看大家的编程经验怎么样了?