Qt_logostrap_CMYK

Handling locked screen event in Qt for Maemo

If you want to pause an application to save battery power when the screen is turned off, you can do this by listening for the locked screen event in Qt for Maemo. However, this is not made easily available through a wrapper function (that I know of), so in this case we’ll need to resort to listening for the right DBus call. (Thanks to Diph from Maemo.org for providing the recipe to make this possible.)

First of all, you’ll need to enable dbus in your project (.pro) file:

maemo5 {
    CONFIG += qdbus
}

Next up, in your .h file you should add the following to import the DBus headers:

#ifdef Q_WS_MAEMO_5
#include <QtDBus/QtDBus>
#endif

And you’ll need to add a slot for the screen state change:

class GameView : public QGraphicsView
{
    Q_OBJECT
public:
    explicit GameView();

public slots:
#ifdef Q_WS_MAEMO_5
    void screenChange(const QDBusMessage &message);
#endif

...

}

Then, in your .cpp file you’ll need to load the Maemo DBus definitions and create a connection. Do this outside any function to have it statically available.

#ifdef Q_WS_MAEMO_5
#include <mce/dbus-names.h>
#include <mce/mode-names.h>

static QDBusConnection dBusConnection = QDBusConnection::systemBus();
#endif

Next up, in the constructor of your class, we’ll set up the necessary DBus connection and interface:

GameView::GameView()
{
#ifdef Q_WS_MAEMO_5
    dBusInterface = new QDBusInterface(MCE_SERVICE, MCE_REQUEST_PATH,
                                       MCE_REQUEST_IF, dBusConnection, this);

    dBusConnection.connect(MCE_SERVICE, MCE_SIGNAL_PATH, MCE_SIGNAL_IF,
                           MCE_DISPLAY_SIG, this, SLOT(screenChange(const QDBusMessage &)));
#endif
}

And finally, we’ll need to fill the function screenChange with something useful. The example below is from my Nanoparticles game and simply pauses the game whenever the screen is locked.

#ifdef Q_WS_MAEMO_5
void GameView::screenChange(const QDBusMessage &message)
{
    QString state = message.arguments().at(0).toString();
    if (!state.isEmpty()) {
        if (state == MCE_DISPLAY_OFF_STRING)
            gameScene.pauseGame();
    }
}
#endif

If you need to check the screen state during startup, have a look at the extra functions that Diph mentions.

Published by

Svenn-Arne Dragly

I'm a physicist and programmer, writing about the stuff I figure out as I go.

Leave a Reply