Menu Home

Android JNI优化

在类加载时获取域和方法的ID

JAVA端:

public class MyClass {
	static {
		System.loadLibrary("mylib");
		/*在加载库的时候一次性获取需要访问的域和方法的ID*/
		getIds();
	}

	public static int someInteger = 0;
	public static native void sayHelloToJNI();
	public static void helloFromJNI() {
		Log.i("MyClass", "Greetings! someInteger = " + someInteger);
	}

	private static native void getId();
}

C/C++端:

 
static jfieldID someIntegerId;
static jfieldID helloFromJNIId;

void JNOCALL Java_com_apress_proandroid_MyClass_sayHelloJNI(JNIEnv *env, jclass clazz) {
	/*这里不在需要获取ID*/

	jint value = (*env)->GetStaticIniField(env, clazz, someIntegerId);
	(*env)->SetStaticIntField(env, clazz, value + 1);

	(*env)->CallStaticVoidMethod(env, clazz, helloFrmoJNIId);
}

/*获取JAVA端的ID*/
void JNICALL Java_com_apress_proandroid_MyClass_getIds(JNIEnv *env, jclass clazz) {
	someIntegerId = (*env)->GetStaticFieldID(env, clazz, "someInteger", "I");
	helloFromJNIId = (*env)->GetStaticMethodID(env, clazz, "helloFromJNI", "()V");
}

ref: 《Android应用性能优化》 p.51

Categories: android应用

Tagged as:

lnmcc