Skip to content

Instantly share code, notes, and snippets.

@ITotalJustice
Last active December 19, 2022 03:20
Show Gist options
  • Save ITotalJustice/73f2a65617af5a8fd46c04fbef8326b8 to your computer and use it in GitHub Desktop.
Save ITotalJustice/73f2a65617af5a8fd46c04fbef8326b8 to your computer and use it in GitHub Desktop.
struct JniHelper
{
JniHelper()
{
vm = g_App->activity->vm;
if (vm->GetEnv((void**)&env, JNI_VERSION_1_6))
{
if (!vm->AttachCurrentThread(&env, NULL))
{
__android_log_print(ANDROID_LOG_INFO, "JNI-TEST", "attaching thread\n");
thread_attached = true;
}
}
}
~JniHelper()
{
if (thread_attached && vm)
{
vm->DetachCurrentThread();
__android_log_print(ANDROID_LOG_INFO, "JNI-TEST", "detaching thread\n");
}
}
JNIEnv* env{};
JavaVM* vm{};
bool thread_attached{};
};
// https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT
// https://developer.android.com/reference/android/content/Intent#ACTION_OPEN_DOCUMENT
void file_picker()
{
JniHelper jni;
// get all the needed classes
const auto ActivityClass = jni.env->FindClass("android/app/Activity");
const auto IntentClass = jni.env->FindClass("android/content/Intent");
// get some constants
const auto ACTION_GET_CONTENT_id = jni.env->GetStaticFieldID(IntentClass, "ACTION_GET_CONTENT", "Ljava/lang/String;");
const auto CATEGORY_OPENABLE_id = jni.env->GetStaticFieldID(IntentClass, "CATEGORY_OPENABLE", "Ljava/lang/String;");
const auto ACTION_GET_CONTENT = (jstring)jni.env->GetStaticObjectField(IntentClass, ACTION_GET_CONTENT_id);
const auto CATEGORY_OPENABLE = (jstring)jni.env->GetStaticObjectField(IntentClass, CATEGORY_OPENABLE_id);
// find constructor and create instance of Intent
const auto IntentClassConstructor = jni.env->GetMethodID(IntentClass, "<init>", "(Ljava/lang/String;)V");
const auto IntentObj = jni.env->NewObject(IntentClass, IntentClassConstructor, ACTION_GET_CONTENT);
// need to set a couple of methods
const auto addCategory = jni.env->GetMethodID(IntentClass, "addCategory", "(Ljava/lang/String;)Landroid/content/Intent;");
const auto setType = jni.env->GetMethodID(IntentClass, "setType", "(Ljava/lang/String;)Landroid/content/Intent;");
// these return itself so you can chain methods together
jni.env->CallObjectMethod(IntentObj, addCategory, CATEGORY_OPENABLE);
jni.env->CallObjectMethod(IntentObj, setType, jni.env->NewStringUTF("*/*"));
// find and call startActivity() (todo: handle result somehow)
const auto startActivityForResult = jni.env->GetMethodID(ActivityClass, "startActivityForResult", "(Landroid/content/Intent;I)V");
jni.env->CallVoidMethod(g_App->activity->clazz, startActivityForResult, IntentObj, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment