Android NDK编程(三)

在本地C语言方法中获取JAVA实例中的属性值

首先,编写JAVA代码:GetJavaPropertyFromNativeC.java

package com.ndk.hello2;

import android.content.Context;
import android.widget.Toast;

public class GetJavaPropertyFromNativeC {

	private Context ctx;
	
	private int 	numberOfJava;
	
	static{
		System.loadLibrary("getJavaPropertyFromNativeC");		
	}
	
	public GetJavaPropertyFromNativeC(Context ctx){
		this.ctx = ctx;
		numberOfJava = 2000;
		nativeInit();
	}
	
	public void showMessage(int value){
		Toast.makeText(ctx, value + " is from native C", Toast.LENGTH_LONG).show();
	}		

	private native void nativeInit();
	
	public  native void nativeBusiness();
}
编写C语言文件:

#include 
#include 
#define LOG_TAG "NDK study"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

jmethodID		mMethodID;
jfieldID		mFieldID;

/*
 * Class:     com_ndk_hello2_GetJavaPropertyFromNativeC
 * Method:    nativeInit
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_ndk_hello2_GetJavaPropertyFromNativeC_nativeInit
  (JNIEnv * env, jobject thiz)
{
	jclass class		 = (*env)->GetObjectClass(env, thiz);
	mMethodID            = (*env)->GetMethodID(env, class, "showMessage", "(I)V");
	mFieldID			 = (*env)->GetFieldID(env, class, "numberOfJava", "I");

	return;
}

/*
 * Class:     com_ndk_hello2_GetJavaPropertyFromNativeC
 * Method:    nativeBusiness
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_ndk_hello2_GetJavaPropertyFromNativeC_nativeBusiness
  (JNIEnv * env, jobject thiz)
{
	jobject mObject              = (*env)->NewGlobalRef(env, thiz);
	jint numOfC;
	jint sum = 0;
	numOfC 				= (*env)->GetIntField(env, mObject, mFieldID);
	sum 				= numOfC + numOfC;
	(*env)->SetIntField(env, mObject, mFieldID, sum);
	(*env)->CallVoidMethod(env, mObject, mMethodID, sum);
	(*env)->DeleteGlobalRef(env, mObject);
	return;
}

在函数Java_com_ndk_hello2_GetJavaPropertyFromNativeC_nativeBusiness中,获取值的方法是:

(*env)->GetIntField(env, mObject, mFieldID);
设置方法:

(*env)->SetIntField(env, mObject, mFieldID, sum);

在这儿使用了NewGlobalRef,其实在这个程序中是不需要的:

全局引用可以跨线程、跨函数使用,而局部引用(默认是局部引用,NewLocalRef、NewObject都是)只可以在当前函数中使用,不可以在全局变量或者静态变量中存起来以供下次使用。




你可能感兴趣的:(Android程序设计)