android中使用jni,ndk的C语言回调方法

android中使用jni,ndk的C语言回调方法

(2010-10-23 14:06:59)

    不说太罗嗦了,回调分为Java代码和C语言代码两部分,我举的例子简单而且是通过调试可以运行的.

    Java代码:

    //====================================================================
    package com.example.hellojni;

    import android.app.Activity;
    import android.util.Log;
    import android.widget.TextView;
    import android.os.Bundle;


    public class HelloJni extends Activity
    {
         public String mJniMsg;
 
         public HelloJni(){}
         @Override
        public void onCreate(Bundle savedInstanceState)
        {
             super.onCreate(savedInstanceState);

             //System.loadLibrary("hello-jni");
             TextView  tv = new TextView(this);
             tv.setText("Eagle,morning!");
             setContentView(tv);
             doCLanguageWork();
        }

        public void myCallbackFunc(String nMsg)
        {
             Log.v("EagleTag","back message:"+nMsg);
        }
        public native String doCLanguageWork();

        static

        {
            System.loadLibrary("hello-jni");
        }
    }

 

    C语言代码部分:

    //====================================================================
    #include <string.h>
    #include <jni.h>

    JNIEXPORT jstring JNICALL
    jobject  gJniObj;
    jclass  gJniClass;
    jmethodID gJinMethod;


    void  GetInstance(JNIEnv* env, jclass obj_class);
    void  DisplayCallBack(JNIEnv* env);

    JNIEXPORT jstring JNICALL
    Java_com_example_hellojni_HelloJni_doCLanguageWork(JNIEnv* env, jobject obj)
    {
         char  tChar[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, "Eagle is really great!......");
    }

    void GetInstance(JNIEnv* env, jclass obj_class) 
    {  
         jmethodID construction_id = (*env)->GetMethodID(env,obj_class, "<init>", "()V"); 
         gJniObj = (*env)->NewObject(env,obj_class, construction_id); 
    } 

    void DisplayCallBack(JNIEnv* env)
    {
         char tChars[256];
 
         strcpy(tChars,"DEBUG:Hello,Eagle");
         (*env)->CallVoidMethod(env,gJniObj,gJinMethod,(*env)->NewStringUTF(env, tChars)); 
    }
    怎么样?不是很难吧?具体能不能理解,就看大家的编程经验怎么样了?

你可能感兴趣的:(C++,c,android,C#,jni)