How to call Java method from C ++ / JNI that takes Android Context parameter

I am trying to call a Java class via C ++ / JNI on Android. In particular, I am trying to call the constructor of this class, which takes an Android context as a parameter. I have no problem successfully making a call if my constructor has no parameters, but when I include the necessary Context as a parameter, I don’t know what my JNI signature should look like, and also doubt that it is possible, since I don’t have access to this context object.

So my question is: is it possible to call the constructor of a Java class that takes the Android context as the only parameter? If so, how? If not, is there a workaround since I need a context to access some Android API classes.

+5
source share
2 answers

I do not believe that this is possible in the form in which you stated. However, knowing the structure of your class, you can always create it as a singleton static instance that is created when your activity starts, thereby making the class reach the required context at that time. It would essentially sit there until you were ready to call from C ++, but really be available to serve your w / context request.

+2
source

When you get the identifier of the constructor method, you just need to specify which one you want. You are currently probably doing something like:

constructor = (*env)->GetMethodID(env, cls, "<init>", "()V");
object = (*env)->NewObject(env, cls, constructor);

Instead, you want to specify the type of the argument when used GetMethodIDand pass it when called NewObject.

constructor = (*env)->GetMethodID(env, cls, "<init>", "(Landroid/content/Context;)V");
object = (*env)->NewObject(env, cls, constructor, context);
0
source

All Articles