Kivy – Android Life Cycle

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)

 

 

Advertisements

2 Responses to Kivy – Android Life Cycle

  1. Jeff says:

    Thank you for writing this post was well as your others regarding Kivy. I do have a question however. In your “on_pause” and “on_resume” functions you are making a call to “self.uiwidget.save/load”. I have not been able to find any documentation on the “uiwidget” attribute. Can you provide some additional information on those save and load functions? Maybe you created yourself?

    Hopefully I haven’t missed something incredibly simple somewhere, but I did just start using Kivy about a week ago.

    Thank you in advance for any information you can share!

  2. brendanscott says:

    uiwidget is a custom widget – what I was using for the user interface. The save and load functions are also custom functions. Assume that there’s an information gap between on_pause and on_resume. Use load and save (or some other functions you name) to bridge this gap – save the data, then load it up again.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: