Kivy - App Life Cycle



A Kivy app goes through various stages from the time it is executed and it stops. The following diagram shows the different stages −

Kivy App Life Cycle

Let us now have a detailed discussion about each of these stages −

Initialize UI

The App class in the Kivy framework is the one that represents a Kivy application. Creating an App object is the first step in the app's life cycle.

from kivy.app import App

Declare a subclass of App class, and override build() method.

from kivy.app import App

class MyApp(App):
   def build(self):
      #UI Design

It in builds the application's UI by either calling the build() method or with the help of the ".kv" file. If required, the app's configurations are loaded from the respective ".ini" file.

Event Loop

Once the user interface is loaded, the App object enters in an infinite event loop.

if __name__ == '__main__':
   MyApp().run()

Various widgets assembled in the interface now absorb the user interactions such as button click or text input, and respond according to corresponding event handlers. In response to the user interaction, the state of any widget or app may be modified.

To run the application, execute the following command from the OS terminal −

Python MyApp.py

While you can run your Kivy app this way on Windows or Linux, you may have to take some additional steps for running it on Android. For Android, you should build an APK (Android Package Kit).

You should use Buildozer, a tool that automates the entire build process. It installs all the prerequisites for python-for-android, including the android SDK and NDK, then builds an APK that can be automatically pushed to the device. Buildozer currently works only in Linux and macOS (for Windows, activate WSL on the machine and then use Buildozer from within WSL)

Pause / Resume

While the app is running, it can be made to pause. For example, if the application window is minimized, or the device itself goes in sleep mode, the pause mode helps in conserving the resources.

Kivy has an on_pause() Event handler. It is called when Pause mode is requested. You should return True if your app can go into Pause mode, otherwise return False and your application will be stopped. You cannot control when the application is going to go into this mode. It's determined by the Operating System and mostly used for mobile devices (Android/iOS) and for resizing.

The app can resume running from the point at which it was paused.

Kivy's on_resume() Event handler gets called when your application is resuming from the Pause mode.

When resuming, the OpenGL Context might have been damaged / freed. This is where you can reconstruct some of your OpenGL state.

Stop

It is when the user closes the app by invoking an appropriate method in the app's code. All the cleanup action is undertaken before the termination of application's run.

Advertisements