August 31th 2014, Qt Android Activity Pausing

August 29th 2014 Declarative Camera Improvements | | September 1st 2014 Qt Swipe Camera

As Android may stop inactive background activities at any time, we need to keep apps in the foreground for continuous tasks. What is annoying, is that an inactive app may not only get stopped, if inactive for too long, but the process may even get killed without any prior notice. This is different from Symbian, where an inactive process is just sitting around doing nothing and taking care of resources by themselves. On Android, there is no chance to keep applications around, because Android may free resources at some unforseeable point by killing inactive processes. We are getting notified via onStop() that an activity is sent to the background, but we do not get notified that an activity is destroyed when its resources are required for the actual foreground process. At least not with Qt, because the onDestroyed() hook does not appear to be forwarded as Qt signal.

In that case there is no chance to get notified before the process is killed, so there is no way to save the actual state or flush file handles. To prevent that, we must catch the inactivation of an app and save the state out, before it gets lost. For that purpose, we install an event filter, which catches the QEvent::ApplicationDeactivate and QEvent::ApplicationActivate events:

class EventFilter: public QObject


   EventFilter(): QObject() {}
   virtual ~EventFilter() {}

   bool eventFilter(QObject *obj, QEvent *event)
      if (event->type() == QEvent::ApplicationDeactivate)
         emit deactivated();
         return true; // the event is handled
      else if (event->type() == QEvent::ApplicationActivate)
         emit activated();
         return true; // the event is handled

      // unhandled events are passed to the base class
      return(QObject::eventFilter(obj, event));


   void deactivated();
   void activated();

If we install the above event filter at the top level application object

// installing the event filter
EventFilter filter;

we can connect to the deactivated() signal and save the application state. Or pause any activities like music playback that should not continue when being inactive.

August 29th 2014 Declarative Camera Improvements | | September 1st 2014 Qt Swipe Camera