首页 > 代码库 > JNI学习2:android 调用C语言方法与C语言调用android方法

JNI学习2:android 调用C语言方法与C语言调用android方法

#include <jni.h>#include <stdio.h>#include <stdlib.h>#include <jni.h>#include <android/log.h>#define LOG_TAG "System.out"//日志乱码时请将项目文件编码设置为UTF-8/**debug级别日志:ANDROID_LOG_DEBUG:级别,LOG_TAG:标签,__VA_ARGS__:日志内容)**/#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)/**info级别日志:ANDROID_LOG_INFO:级别,LOG_TAG:标签,__VA_ARGS__:日志内容)**/#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)extern "C" {/***java语言String转C语言char***/ char* JstringTochar(JNIEnv *env, jstring jstr) {	char* rtn = NULL;	jclass classtring = env->FindClass("java/lang/String");	jstring strencode = env->NewStringUTF("GB2312");	jmethodID mid = env->GetMethodID(classtring, "getBytes","(Ljava/lang/String;)[B");	jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);	jsize alen = env->GetArrayLength(barr);	jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);	if (alen > 0) {		rtn = (char*) malloc(alen + 1);		memcpy(rtn, ba, alen);		rtn[alen] = 0;	}	env->ReleaseByteArrayElements(barr, ba, 0);	return rtn;}JNIEXPORT jstring Java_com_example_ndktest_JNIProvideer_hello(JNIEnv *env,jobject obj) {	LOGD("%s", "haha");	return env->NewStringUTF("Hello from JNI !");}/***2个整数相加***/JNIEXPORT jint Java_com_example_ndktest_JNIProvideer_add(JNIEnv *env,jobject obj,jint x,jint y){	return x+y;}/***字符串转换***/JNIEXPORT jstring Java_com_example_ndktest_JNIProvideer_sayHello(JNIEnv *env,jobject obj,jstring jstr){	char* p=JstringTochar(env,jstr);	LOGI("sss%s",p);	//strcat(p,helloWord)表示helloWord?拼接到p后面	return env->NewStringUTF(strcat(p,"helloWord"));}/***整数数组每一个元素加10***/JNIEXPORT jintArray Java_com_example_ndktest_JNIProvideer_getIntArray(JNIEnv *env,jobject obj,jintArray jintarr){	//获取数组长度	int len=env->GetArrayLength(jintarr);	LOGI("len=%d",len);	//获取整数数组地址	jint* arr=env->GetIntArrayElements(jintarr,0);	for (int i=0;  i < len; i++) {		*(arr+i)+=10;	}	return jintarr;}/***主动调用java对象中方法String getString() * ()Ljava/lang/String;表示参数为空,返回值为String***/JNIEXPORT void Java_com_example_ndktest_JNIProvideer_getJavaMethodForGetString(JNIEnv *env,jobject obj) {	jclass classz=env->FindClass("com/example/ndktest/JNIProvideer");	if(classz==0){		LOGI("can‘t find class");	}else{		LOGI("find class");	}	jmethodID javaMethod=env->GetMethodID(classz,"getString","()Ljava/lang/String;");	if(javaMethod==0){		LOGI("can‘t find menthod");	}else{		LOGI("find menthod");	}    jstring result= (jstring)env->CallObjectMethod(obj,javaMethod);	char* p=JstringTochar(env,result);	LOGI("result=%s",p);}/***主动调用java对象中方法int getAdd(int x,int y) * (II)I表示参数为2个整数,返回值为整数***/JNIEXPORT void Java_com_example_ndktest_JNIProvideer_getJavaMethodForGetAdd(JNIEnv *env,jobject obj) {	jclass classz=env->FindClass("com/example/ndktest/JNIProvideer");	if(classz==0){		LOGI("can‘t find class");	}else{		LOGI("find class");	}	jmethodID javaMethod=env->GetMethodID(classz,"getAdd","(II)I");	if(javaMethod==0){		LOGI("can‘t find menthod");	}else{		LOGI("find menthod");	}	int result= env->CallIntMethod(obj,javaMethod,7,7);	LOGI("result=%d",result);}/***主动调用java对象中方法void getvoidMethod(String x) * (Ljava/lang/String;)V表示参数为String,返回值为空***/JNIEXPORT void Java_com_example_ndktest_JNIProvideer_getJavaMethodForGetvoidMethod(JNIEnv *env,jobject obj) {	jclass classz=env->FindClass("com/example/ndktest/JNIProvideer");	if(classz==0){		LOGI("can‘t find class");	}else{		LOGI("find class");	}	jmethodID javaMethod=env->GetMethodID(classz,"getvoidMethod","(Ljava/lang/String;)V");	if(javaMethod==0){		LOGI("can‘t find menthod");	}else{		LOGI("找到方法");	}	env->CallVoidMethod(obj,javaMethod,env->NewStringUTF("abc"));}}

  

package com.example.ndktest;import android.util.Log;public class JNIProvideer {  static{	  System.loadLibrary("ndkTest");  }  public native int add(int x,int y);  public native String sayHello(String s);  public native int[] getIntArray(int[] ints);  public native String hello();  public native void getJavaMethodForGetString();  public native void getJavaMethodForGetAdd();  public native void getJavaMethodForGetvoidMethod();  /**   *让c语言主动调用的方法 * @return */public String getString(){	  return "hello";  }/** *让c语言主动调用的方法* @return*/  public int getAdd(int x,int y){	  return x+y;  }  /**   * 让c语言主动调用的方法  * @return  */    public void getvoidMethod(String x){          Log.i("test", "输入值:"+x);    }}

  

package com.example.ndktest;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity {    public native String hello();	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.fragment_main);		Button tx=  (Button) findViewById(R.id.test);		tx.setOnClickListener(new OnClickListener() {						@Override			public void onClick(View v) {				JNIProvideer jNIProvideer=new JNIProvideer();				String result="";								//result=jNIProvideer.hello();								//int add=jNIProvideer.add(4, 5);				//result=add+"";								//int[] intarray=jNIProvideer.getIntArray(new int[]{3,5,5,4});								//for (int i = 0; i < intarray.length; i++) {				//result+=intarray[i];				//}								//result=jNIProvideer.sayHello("say:");				//jNIProvideer.getJavaMethodForGetString();				//jNIProvideer.getJavaMethodForGetAdd();				jNIProvideer.getJavaMethodForGetvoidMethod();				//Toast.makeText(getApplicationContext(), result, 0).show();			}		});		}	}

  

JNI学习2:android 调用C语言方法与C语言调用android方法