Kivy – Android Life Cycle
July 23, 2014 2 Comments
If your app is a stand alone app which doesn’t interact with the rest of the Android environment, then you don’t have to worry about life cycles. For everyone else, welcome to the Android way of doing things. The Android life cycle reflects a design decision by the Android developers that any app needs to be able to be interrupted at any time without warning for no reason – originally I think this was in order to receive phone calls and/or account for low phone resources. However, it still applies to devices which don’t even have a cell phone radio.
Android deals with this primarily through calling on_pause and on_resume methods on apps (actually onPause and onResume in Java). If the app wants to do something there (eg save/restore current data!), well and good. Android calls on_pause() when it returns Android suspends the app until someone brings the app to the foreground again, at which time on_resume() is called. The Android lifecycle is actually more complicated than this but let’s not sweat the details.
Kivy allows you to implement the on_pause and on_resume simply by adding these methods to your app instance. Some sample code:
class GridderApp(App): # stuff deleted def on_pause(self): self.uiwidget.save(path =".", filename=PAUSE_FILE_NAME) return True # app sleeps until resume return False to stop the app def on_stop(self): pass def on_resume(self): self.uiwidget.load(path=".", filename=PAUSE_FILE_NAME, store_save= False)