Search code examples
qtqmlqt-quickqtquickcontrols2

How to get mobile app lifecycle events on QtApp


I am programming an app in Qt 5.9.4 commercial license. My app runs on Android and iOS.

Question:
Is there a way in Qt to detect usual mobile device events like:
- Device display switched off
- Device went to background after user presses home button on iOS/Android
- back button pressed on Android etc

There are a bunch of these events that each of the platform Android and iOS trigger.

If there is class/module in Qt that is relaying these events back then I wouldn't have to do the extra work of writing native(java and objective-c) classes to get these events inside my QtApp.


Solution

  • Most of these events are handeled by Qt itself and you can get them through classical means. Qt tries to hide android specific stuff as good as possible and delivers those though events etc. as you would get them on a desktop application.

    The back button press triggers a QCloseEvent that is sent to the primary window. You can install an event filter on the object from C++ it to intercept it. For qml it's the Window::closing signal.

    Since Qt does not support background execution of activities, the background press is propably reported as close event as well - or it quits the application directly.

    For the DIsplay switch of I don't now for sure, but maybe the QGuiApplication::applicationStateChanged signal does report it as Qt::ApplicationSuspended or another of those states - simply try it out! (this might be the case for other events as well)


    Short Hint for Android: If you however want something Qt does not handle, you can always just create a custom Java activity that extends the QtActivity and use it in the manifest. From there on you can use the JNI to interact with Java from C++ and vice versa. If you need to do so, have a look at the Qt Android Extras - They make using the JNI much easier and provide a bunch of nice wrapper classes and utility methods in the QtAndroid namespace that can come in very handy.