Android将参数传递给Native Activity

时间:2012-10-11 13:55:09

标签: android android-ndk native-activity

我的Android应用程序包含两个活动:“。MainActivity”和“android.app.NativeActivity”。后者完全用C ++实现。在按钮上单击“.MainActivity”,我启动一个尝试传递一些参数的本机:

public void pressedButton(View view)
{
    Intent intent = new Intent(this, android.app.NativeActivity.class);
    intent.putExtra("MY_PARAM_1", 123);
    intent.putExtra("MY_PARAM_2", 321);
    startActivity(intent);
}

如何从android.app.NativeActivity的入口点(即C函数void android_main(struct android_app* state))中获取MY_PARAM_1和MY_PARAM_2?

1 个答案:

答案 0 :(得分:12)

android_app结构中,有activity类型ANativeActivity*的数据成员。在后者内部,有JavaVM *vm和误导性的jobject clazzclazz实际上是一个符合JNI的对象实例指针,指向类型为android.app.NativeActivity的Java对象,该对象具有Activity个方法,包括getIntent()

那里也有一个JNIEnv,但看起来它并没有附加到活动的主线程上。

使用JNI调用来检索意图,然后从意图中获取额外内容。它是这样的:

JNIEnv *env;
state->activity->vm->AttachCurrentThread(&env, 0);

jobject me = state->activity->clazz;

jclass acl = env->GetObjectClass(me); //class pointer of NativeActivity
jmethodID giid = env->GetMethodID(acl, "getIntent", "()Landroid/content/Intent;");
jobject intent = env->CallObjectMethod(me, giid); //Got our intent

jclass icl = env->GetObjectClass(intent); //class pointer of Intent
jmethodID gseid = env->GetMethodID(icl, "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;");

jstring jsParam1 = env->CallObjectMethod(intent, gseid, env->NewStringUTF("MY_PARAM_1"));
const char *Param1 = env->GetStringUTFChars(jsParam1, 0);
//When done with it, or when you've made a copy
env->ReleaseStringUTFChars(jsParam1, Param1);

//Same for Param2