Search code examples
javaandroidandroid-ndkjava-native-interface

Calling getUnicodeChar method from C++ in Android


I need unicode value of the key I pressed on Android's soft keyboard on C++ code but it looks like NativeActivity does not expose the 'getUnicodeChar' method. So I tried to call it with JNI but GetMethodID for that function returns '0'. This is my first time with the JNI so I might be doing something very wrong. I guess I have to give my 'AInputEvent' to Java somehow but I'm not sure how. This is the code I wrote:

JavaVM* java_vm = and_app->activity->vm; 
JNIEnv* jni_env = and_app->activity->env; 

JavaVMAttachArgs attach_args; 
attach_args.version = JNI_VERSION_1_6; 
attach_args.name = "NativeThread"; 
attach_args.group = NULL; 

jint result = java_vm->AttachCurrentThread(&jni_env, &attach_args); 
if(result == JNI_ERR)
{ 
    return 0;
}

jclass class_key_event = jni_env->FindClass("android.view.KeyEvent");
jmethodID method_get_unicode_char = jni_env->GetMethodID(class_key_event, "getUnicodeChar", "()I");
int return_key = jni_env->CallIntMethod(class_key_event, method_get_unicode_char);
java_vm->DetachCurrentThread();

return return_key;

Solution

  • The syntax for FindClass is quite special, and it requires what the JNI documentation calls a "a fully-qualified class name", which means a package name with the dots replaced by slashes.

    In your case, using:

    jclass class_key_event = jni_env->FindClass("android/view/KeyEvent");
    

    should make your code work, or at least push it in the right direction!