Getting a Context from a NativeActivity
Asked Answered
I

1

8

I have an application using NativeActivity. I want to call out into Java to do something that requires a Context (e.g., accessing TelephonyManager to query the IMEI).

How do I get a valid Context for my activity?

The ANativeActivity structure contains a variety of useful data for my application, such as the JavaVM, and JNI environment, etc. It also contains a jobject pointing at my NativeActivity's class object. What it doesn't contain is a jobject pointing at the NativeActivity's instance. I don't see anything useful in struct android_app, either.

It must be possible to do this; any ideas how?

Ishii answered 2/9, 2011 at 14:39 Comment(2)
Possible double question. Check this out #4450364Essie
Nope, that question refers to old-style NDK (where it was strictly call-out from Java), while I'm using new-style NativeActivity NDK (where the main app is written in native code and calls into Java).Ishii
J
8

Despite its name the clazz member of ANativeActivity struct is actually pointing to android.app.NativeActivity instance.
Check this post for an example of using a JNI call from the Native Activity to Java code.

Jeter answered 2/9, 2011 at 15:33 Comment(2)
The docs in the header say it's a class, too --- but yes, now I actually try to use it it's obviously the instance rather than the class. Thanks!Ishii
Yes, that's true. The doc is a confusing one as it describes clazz field as The NativeActivity Java class. The only weak hint is clazz type: jobject instead of jclass. Nevertheless it's worth a bug/feature-request for docs improvement to be posted.Jeter

© 2022 - 2024 — McMap. All rights reserved.