Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 426
user3252937 Avatar asked Dec 12 '22 07:12

user3252937


1 Answers

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);
app->activity->vm->DetachCurrentThread();

you also need to add this code in your manifest:

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

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
like image 127
user3252937 Avatar answered Dec 13 '22 21:12

user3252937