Android-NDK开发之第四个例子--用C/C++调用Java


  用C/C++调用Java的方法我没有去研究,也不知道从哪里开始研究,对Linux我了解到很少,希望有朋友可以给些资料,我的水平很差,望大家多多包涵。

  这个例子是别人的代码,我忘记从来里弄来的了,先对原作者表示抱歉。同时代码也被我修改过,再次道歉。

  而此文和别的文章一样,只是作为我平时学习积累的验证。

 

  1. Android.mk文件:

LOCAL_SRC_FILES参数用空格隔开

 

LOCAL_PATH:=$(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE:=native LOCAL_SRC_FILES:=geolo.cpp my_jni.h include $(BUILD_SHARED_LIBRARY) 

 

2. geolo.cpp

先用FindClass方法找到java类,有点类似java的反射用LoadClass

再用CallObjectMethod方法调用Java类的函数。

#include "my_jni.h" jobject getInstance(JNIEnv* env, jclass obj_class){ jmethodID construction_id = env->GetMethodID(obj_class, "<init>", "()V"); jobject obj = env->NewObject(obj_class, construction_id); return obj; } JNIEXPORT jstring JNICALL Java_com_easepal_geolo_CActivityMain_stringFromJNI(JNIEnv* env, jobject thiz){ jstring str; jclass java_class = env->FindClass("com/easepal/geolo/CForCall"); if (java_class == 0){ return env->NewStringUTF("not find class!"); } jobject java_obj = getInstance(env, java_class); if (java_obj == 0){ return env->NewStringUTF("not find java OBJ!"); } jmethodID java_method = env->GetMethodID(java_class, "GetJavaString", "()Ljava/lang/String;"); if(java_method == 0){ return env->NewStringUTF("not find java method!"); } str = (jstring)env->CallObjectMethod(java_obj, java_method); return str; } 

 

3. my_jni.h

 

/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_easepal_geolo_CActivityMain */ #ifndef _Included_com_easepal_geolo_CActivityMain #define _Included_com_easepal_geolo_CActivityMain #ifdef __cplusplus extern "C" { #endif /* * Class: com_easepal_geolo_CActivityMain * Method: stringFromJNI * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_easepal_geolo_CActivityMain_stringFromJNI(JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif 

 

4. CActivityMain.java

package com.easepal.geolo; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class CActivityMain extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText( stringFromJNI("hello") ); setContentView(tv); } static { System.loadLibrary("native"); } public native String stringFromJNI(String str); } 

 

5. CForCall.java

package com.easepal.geolo; public class CForCall{ public CForCall(){}; //public ~CForCall(){}; public String GetJavaString(){ String str; str = "123456"; return str; } }  

 

你可能感兴趣的:(java,String,Class,include,library,construction)