Android平台Kivy应用关闭后无法立即重启问题求助
Hey, I've run into nearly identical issues with Kivy Android apps before—let's break down what's happening and how to fix it.
The Problem
I successfully packaged my Kivy app for Android using Buildozer, but I'm hitting an annoying bug: when I press the Home button to pause the app, then close it via the task manager, I can't immediately reopen it. Instead, I get a black screen (with a slightly lighter bottom bar). The app works fine otherwise, and if I wait a while, it starts up normally again.
This app is meant to display local .ttf font files from a folder, and runs without issues during regular use—only this restart scenario causes problems.
Minimal Reproducible Example
main.kv
<MainScreen>: Button: id: fontbutton font_size: 100 text: 'press here' on_press: root.updatebutton()
main.py
from kivy.app import App from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout class MainScreen(FloatLayout): def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.i = 0 self.fontarray = ['Waree', 'Umpush', 'TlwgTypo', 'TlwgTypist', 'TlwgMono', 'Sawasdee', 'Purisa', 'Norasi', 'Loma', 'Laksaman', 'Kinnari', 'Garuda'] def updatebutton(self): if self.i >= 12: self.i = 0 self.ids.fontbutton.text = str(self.fontarray[self.i]) self.ids.fontbutton.font_name = 'usethesefonts/' \ + str(self.fontarray[self.i]) + '.ttf' self.i = self.i + 1 class MainApp(App): def build(self): themainscreen = MainScreen() return themainscreen if __name__=="__main__": MainApp().run()
Environment Details
- Kivy 1.10.0
- Python 2.7.15rc1
- Cython 0.23
- Buildozer 0.34
- Virtualization: Oracle VM VirtualBox
- OS: Ubuntu 18.04 (64-bit, bionic)
buildozer.spec (Uncommented Sections)
[app] title = sf2 package.name = sfont2 package.domain = org.test source.dir = . version = 1 requirements = kivy orientation = all osx.python_version = 2 osx.kivy_version = 1.10.0 fullscreen = 1 android.minapi = 13 [buildozer] log_level = 2 warn_on_root = 1
Troubleshooting & Fixes
This black screen issue almost always boils down to unreleased resources (in this case, fonts) or Android process lingering that locks resources. Here are actionable fixes to try:
1. Handle App Lifecycle Events to Clean Up Resources
Kivy's App class has lifecycle hooks that let you clean up resources when the app pauses or stops. Add these methods to your MainApp class to ensure fonts are released properly:
class MainApp(App): def build(self): themainscreen = MainScreen() return themainscreen def on_stop(self): # Clear the font reference to release resources if hasattr(self.root.ids, 'fontbutton'): self.root.ids.fontbutton.font_name = None # Force garbage collection to free up unused memory import gc gc.collect() def on_pause(self): # Temporarily release the font when pausing if hasattr(self.root.ids, 'fontbutton'): self.root.ids.fontbutton.font_name = None return True # Allow the app to pause def on_resume(self): # Re-load the last used font when resuming if hasattr(self.root, 'i') and self.root.i > 0: current_font = self.root.fontarray[self.root.i - 1] self.root.ids.fontbutton.font_name = f'usethesefonts/{current_font}.ttf' self.root.ids.fontbutton.text = current_font
2. Tweak Buildozer Config to Fix Process Lingering
Add these lines to the [app] section of your buildozer.spec to force Android to clean up the app process properly:
android.dont_keep_activity = True android.launch_mode = singleTask android.allow_backup = False
android.dont_keep_activitytells Android to destroy the app's activity when it's paused, preventing lingering processes.singleTaskensures each app launch starts a fresh task instance.
3. Upgrade Dependencies (Highly Recommended)
Your Kivy and Buildozer versions are quite outdated, and they have known bugs with Android lifecycle and resource management. Try upgrading:
- Kivy: Move to 1.11.1 (the last version supporting Python 2) or newer if you can migrate to Python 3.
- Buildozer: Update to the latest stable release (e.g., 0.49+).
- Python: Consider migrating to Python 3 since Python 2 is no longer supported, and newer Kivy versions have better Python 3 support.
4. Fix Font Loading Paths
Ensure your font files are correctly packaged and loaded using Kivy's resource system, which handles Android paths better:
Modify the updatebutton method in MainScreen:
from kivy.resources import resource_find def updatebutton(self): if self.i >= 12: self.i = 0 font_name = self.fontarray[self.i] # Use resource_find to locate the font file correctly font_path = resource_find(f'usethesefonts/{font_name}.ttf') if font_path: self.ids.fontbutton.text = font_name self.ids.fontbutton.font_name = font_path else: self.ids.fontbutton.text = f'Font {font_name} not found' self.i += 1
How to Test
- Apply the fixes above, then re-package the app with Buildozer.
- Install it on your Android device, press Home to pause the app.
- Close it via the task manager, then immediately reopen it—check if the black screen is gone.
内容的提问来源于stack exchange,提问作者bob-T

