用C/C++调用Java的方法我没有去研究,也不知道从哪里开始研究,对Linux我了解到很少,希望有朋友可以给些资料,我的水平很差,望大家多多包涵。
这个例子是别人的代码,我忘记从来里弄来的了,先对原作者表示抱歉。同时代码也被我修改过,再次道歉。
而此文和别的文章一样,只是作为我平时学习积累的验证。
1. Android.mk文件:
LOCAL_SRC_FILES参数用空格隔开
1
2
3
4
5
|
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类的函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#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);
returnobj;
}
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){
returnenv->NewStringUTF("not find class!");
}
jobject java_obj = getInstance(env, java_class);
if(java_obj == 0){
returnenv->NewStringUTF("not find java OBJ!");
}
jmethodID java_method = env->GetMethodID(java_class,"GetJavaString","()Ljava/lang/String;");
if(java_method == 0){
returnenv->NewStringUTF("not find java method!");
}
str = (jstring)env->CallObjectMethod(java_obj, java_method);
returnstr;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/* 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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
packagecom.easepal.geolo;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.widget.TextView;
publicclassCActivityMainextendsActivity {
/** Called when the activity is first created. */
@Override
publicvoidonCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TextView tv =newTextView(this);
tv.setText( stringFromJNI("hello") );
setContentView(tv);
}
static{
System.loadLibrary("native");
}
publicnativeString stringFromJNI(String str);
}
|
1
2
3
4
5
6
7
8
9
10
11
|
packagecom.easepal.geolo;
publicclassCForCall{
publicCForCall(){};
//public ~CForCall(){};
publicString GetJavaString(){
String str;
str ="123456";
returnstr;
}
}
|