在 ndk 应用程序中访问 android 上下文 [英] Access android context in ndk application

查看:14
本文介绍了在 ndk 应用程序中访问 android 上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在我的 ndk 应用程序中传递/获取 android 上下文对象.我想通过 jni 接口在我的 ndk 应用程序中使用 SharedPreferences .要获取 SharedPreferences 对象的实例,我需要在 Context 对象上调用 getSharedPreferences().但我无权访问上下文对象.

Is there any way in which I can pass/get an object of android context in my ndk appliation. I want to use SharedPreferences in my ndk application via jni interface. To get an instance of SharedPreferences object, I need to call getSharedPreferences() on Context object. But I do not have access to the context object.

如何从 NDK 读取和写入 xml 文件?

How can I read and write an xml file from NDK ?

任何指针将不胜感激.

推荐答案

没有什么特别需要做的,就像普通的JNI机制一样.您需要获取指向上下文对象的指针,然后检索要调用的方法 ID,然后使用所需的 args 调用它.

There is nothing special you have to do, it is just like regular JNI mechanism. You need to get a pointer to the context object, then retrieve the method ID you want to call and then invoke it with the args you want.

当然,这听起来非常简单,但在代码中它变得非常混乱,因为所有的检查和 JNI 调用.

Of course in words it sounds super straightforward, but in code it gets really messy since the all the checks and JNI calls.

因此,在我看来,我不会尝试从本机/JNI 代码实现整个事情,而是我将在 Java 中实现一个辅助方法,该方法可以制作所有内容并接收所需的数据来读取/写入首选项.

So in my opinion i will not try to implement the whole thing from native/JNI code, instead i will implement a helper method in Java that makes all the stuff and just receives the needed data to read/write the preference.

这将大大简化您的本机代码,并使其更易于维护.

That will simplify a lot your native code and it will make it easier to maintain.

例如:

//Somewhere inside a function in your native code
void Java_com_example_native_MainActivity_nativeFunction(JNIEnv* env, jobject thiz)
{
    jclass cls = (*env)->FindClass(env,"PreferenceHelper");
    if (cls == 0) printf("Sorry, I can't find the class");

    jmethodID set_preference_method_id;

    if(cls != NULL)
    {
        set_preference_method_id = (*env)->GetStaticMethodID(env, cls, "setPreference", "(Ljava/lang/String;Ljava/lang/StringV");

        if(set_preference_method_id != NULL )
        {
            jstring preference_name = (*env)->NewStringUTF(env, "some_preference_name");
            jstring value = (*env)->NewStringUTF(env, "value_for_preference");

            (*env)->CallStaticVoidMethod(env, cls, get_main_id, preference_name, value);
        }
    }
}

请注意,我只是从内存中编写代码,所以不要开箱即用.

这篇关于在 ndk 应用程序中访问 android 上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆