chaquo / chaquopy

Chaquopy: the Python SDK for Android
https://chaquo.com/chaquopy/
MIT License
748 stars 127 forks source link

Support standard library `webbrowser` module #1149

Open mhsmith opened 1 month ago

mhsmith commented 1 month ago

The code to open a browser on Android would be something like this:

from android content import Intent
from android.net import Uri

intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"))
context.startActivity(intent)

However, Android doesn't provide any public way to get a context unless you already have a reference to a UI object. Within Chaquopy, we already have a reference to the global Application context. But in order to upstream this to CPython, we'd need to get the context in JNI using something like this:

jclass activityThread = (*env)->FindClass(env,"android/app/ActivityThread");
jmethodID currentActivityThread = (*env)->GetStaticMethodID(env, activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;");
jobject activityThreadObj = (*env)->CallStaticObjectMethod(env, activityThread, currentActivityThread);

jmethodID getApplication = (*env)->GetMethodID(env, activityThread, "getApplication", "()Landroid/app/Application;");
jobject context = (*env)->CallObjectMethod(env, activityThreadObj, getApplication);

Although ActivityThread is a hidden class, the relevant methods are all marked with @UnsupportedAppUsage, which means Google is aware that applications are using them, so they haven't blocked them.