用C/C++調(diào)用Java的方法我沒有去研究,,也不知道從哪里開始研究,,對Linux我了解到很少,希望有朋友可以給些資料,,我的水平很差,,望大家多多包涵。
這個例子是別人的代碼,,我忘記從來里弄來的了,,先對原作者表示抱歉。同時代碼也被我修改過,,再次道歉,。
而此文和別的文章一樣,,只是作為我平時學習積累的驗證。
1. Android.mk文件:
LOCAL_SRC_FILES參數(shù)用空格隔開
- 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方法調(diào)用Java類的函數(shù)。
- #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
-
- #include <jni.h>
-
- #ifndef _Included_com_easepal_geolo_CActivityMain
- #define _Included_com_easepal_geolo_CActivityMain
- #ifdef __cplusplus
- extern "C" {
- #endif
-
-
-
-
-
- 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 {
-
- @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 String GetJavaString(){
- String str;
- str = "123456";
- return str;