如何用Python Kivy开发带导航的WebView应用:外部链接与返回键设置
Hey there! Let's tackle your two Kivy Android app requirements step by step with Python-native solutions:
1. Open External Links in Device Browser
Even though you mentioned only having a Java Intent-based solution, we can replicate this logic in Python using pyjnius to interface with Android's native APIs. Here's how to adjust your embedded WebView setup:
First, add pyjnius to your buildozer.spec requirements (so it gets included in your Android build). Then, modify your WebView's client to intercept and redirect external links:
from jnius import autoclass, cast # Import Android classes via pyjnius PythonActivity = autoclass('org.kivy.android.PythonActivity') Intent = autoclass('android.content.Intent') Uri = autoclass('android.net.Uri') WebViewClient = autoclass('android.webkit.WebViewClient') # Custom client to handle link loading class CustomWebViewClient(WebViewClient): def shouldOverrideUrlLoading(self, view, url): # Replace "your-target-site.com" with your app's core website domain if "your-target-site.com" not in url: # Launch device browser for external links intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse(url)) current_activity = cast('android.app.Activity', PythonActivity.mActivity) current_activity.startActivity(intent) return True # Tell WebView we handled this link return False # Let WebView load internal site links # Attach the custom client to your WebView instance web_view.setWebViewClient(CustomWebViewClient())
This checks if the URL belongs to your target website—if not, it triggers the device's default browser via an Intent, just like the Java approach but in Python.
2. Minimize App on Back Press Instead of Exiting
To override the back button behavior and minimize the app, add this logic to your main Kivy app class, using pyjnius to call Android's native task management:
from jnius import autoclass from kivy.app import App PythonActivity = autoclass('org.kivy.android.PythonActivity') class YourApp(App): def on_back_press(self): # Move the app to the background (minimize) current_activity = PythonActivity.mActivity current_activity.moveTaskToBack(True) return True # Prevent default app exit behavior
Returning True tells Kivy you've handled the back press event, so it won't close the app.
Quick Tips
- Ensure
android.permission.INTERNETis added to yourbuildozer.specto enable web access. - Tweak the domain check in the link handler to account for subdomains or HTTPS/HTTP variations if needed.
内容的提问来源于stack exchange,提问作者Sam Sk

