call android activity from jni directly from c++ process without java side-ThrowExceptions

Exception or error:

I’m using Eclipse and developing an Android app which have a Java coding and also jni C++ code.

I’m trying to start an activity of Java directly from the jni without touching the Java side.
Is there a way to do so?

How to solve:

ok I found out how to do it finally! it’s work!
The only thing you need to change is write your package name and class name in
NewStringUTF for example: NewStringUTF("org.samples.test.MyClass")

note: app is your android_app*

JNIEnv *env;
JavaVM* lJavaVM = app->activity->vm;
app->activity->vm->AttachCurrentThread(&env, NULL);

jobject lNativeActivity = app->activity->clazz;
jclass intentClass = env->FindClass("android/content/Intent");
jstring actionString =env->NewStringUTF("Package Name. Class Name");
jmethodID newIntent = env->GetMethodID(intentClass, "<init>", "()V");
jobject intent = env->AllocObject(intentClass);
env->CallVoidMethod(intent, newIntent);
jmethodID setAction = env->GetMethodID(intentClass, "setAction","(Ljava/lang/String;)Landroid/content/Intent;");
env->CallObjectMethod(intent, setAction, actionString);
jclass activityClass = env->FindClass("android/app/Activity");
jmethodID startActivity = env->GetMethodID(activityClass,"startActivity", "(Landroid/content/Intent;)V");
jobject intentObject = env->NewObject(intentClass,newIntent);
env->CallVoidMethod(intentObject, setAction,actionString);
env->CallVoidMethod(lNativeActivity, startActivity, intentObject);

you also need to add this code in your manifest:

<activity android:name=".JavaActivity"
          android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
        <action android:name="you.package.path.JavaActivity" />

        <category android:name="android.intent.category.DEFAULT" />

Leave a Reply

Your email address will not be published. Required fields are marked *