Open URL from Android NDK application

24

There are two solutions for opening URL from Android NDK application: doing it from Java and doing it from the native code.

Open URL from Java

Opening URL from Java is a piece of cake:

Intent view = new Intent(Intent.ACTION_VIEW, Uri.parse("https://samblog.com"));
startActivity(view);

Open URL from C++ with JNI

JNI offers the same way but in a bit tricky manner:

android_app* android;
// ...
JNIEnv* env;
android->activity->vm->AttachCurrentThread(&env, nullptr);
jstring url_string = env->NewStringUTF("https://samblog.com");
jclass uri_class = env->FindClass("android/net/Uri");
jmethodID uri_parse = env->GetStaticMethodID(uri_class, "parse", "(Ljava/lang/String;)Landroid/net/Uri;");
jobject uri = env->CallStaticObjectMethod(uri_class, uri_parse, url_string);
jclass intent_class = env->FindClass("android/content/Intent");
jfieldID action_view_id = env->GetStaticFieldID(intent_class, "ACTION_VIEW", "Ljava/lang/String;");
jobject action_view = env->GetStaticObjectField(intent_class, action_view_id);
jmethodID new_intent = env->GetMethodID(intent_class, "<init>", "(Ljava/lang/String;Landroid/net/Uri;)V");
jobject intent = env->AllocObject(intent_class);
env->CallVoidMethod(intent, new_intent, action_view, uri);
jclass activity_class = env->FindClass("android/app/Activity");
jmethodID start_activity = env->GetMethodID(activity_class, "startActivity", "(Landroid/content/Intent;)V");
env->CallVoidMethod(android->activity->clazz, start_activity, intent);
android->activity->vm->DetachCurrentThread();
Share this page:

See also how to:

How to call your native functions in Android NDK application from Java
How to use JNIEnv::FindClass on Android and what you should know about it
How to find all Clang arguments that used to build native code in Android Studio
Select target architectures in Android Studio build
The most simple example how to show a message box on Android application