2

我正在使用 JNI 通过 Qt 从 Android 获取音乐库。我调用以下 Java 方法(已经实现),

public String getArtists(Context context)
...

我需要能够获取应用程序的上下文才能使其工作。

如果有帮助,当我使用 Java 时,以下代码提供了正确的上下文。

MainActivity.this

有人可以帮助解决这个问题吗?

非常感谢!

4

1 回答 1

3

It will depend where you are making the call. Ideally you will cache the MainActivity pointer in C++.

One way to cache a pointer to use in a later JNI call is to add a native function in java such as native void onCreateNative() to you MainActivity class. In C++ you'll implement the method and cache the "thiz" pointer:

JNIEXPORT void JNICALL com_package_MainActivity_onCreateNative(JNIEnv *env, jobject thiz)
{
    gCachedActivity = env->NewGlobalRef(thiz);
}

Now you can use gCachedActivity where you would have used MainActivity.this

env->CallObjectMethod(obj, s_getArtistsGetArtistsMethodID, gCachedActivity);

Of course replacing obj with the object you are calling the method on.

Lastly onCreateNative() should be called in the onCreate() method of MainActivity.

于 2013-08-18T19:41:20.830 回答