maanantai 16. marraskuuta 2015

How to prevent screen blanking in Sailfish


I was playing with simple visual timer to help kids focus onto given task and needed a way to prevent a screen from turning off (aka blanking) during the countdown.

As it happens, this isn't very difficult, but information on how to do it is a bit scattered. As far as I know the method described below is allowed withing Jolla store, but I haven't published this timer yet (I'll need to add user-selectable countdowns first, in addition of fixed ones) so I can't be completely sure.

This can't be done (yet?) with QML only, so some C++ is required, but fortunately no deeper magic is required.

First, you'll need to create simple helper object that can be called fromQML.

Header (note: when working with Qt classes the class definition, even simple one like this, absolutely must be in external header (.h) file; you can't include it in .cpp file as it will fail mysteriously to compile. Want to guess how I found this out? *eye roll*)

class BlankPrevent : public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE void prevent(int prevent);
};

Source:

void BlankPrevent::prevent(int prevent) {

    QDBusConnection system = QDBusConnection::connectToBus(QDBusConnection::SystemBus, "system");
    QDBusInterface interface("com.nokia.mce", "/com/nokia/mce/request", "com.nokia.mce.request", system);

    if (prevent) {
        interface.call(QLatin1String("req_display_blanking_pause"));
    } else {
        interface.call(QLatin1String("req_display_cancel_blanking_pause"));
    }
}

Above is shamelessly borrowed from this source, so credit where credit is due. Also you'll need add proper includes, as well as "QT += dbus" to your .pro file.

If your app is C++ only, you can simply call this function every now and then and it's done. From QML you'll need a bit more. First, add component registration to your C++ main();

qmlRegisterType("harbour.myapp.CustomComponents", 1, 0, "BlankPrevent");

And now it can be added as an item in your QML;

import harbour.myapp.CustomComponents 1.0

...

BlankPrevent { // as part of SilicaFlickable from example
            id: blanker
        }

...

property int refresh: 0;

Timer {
        interval: 15000; // adjust as needed
        running: true;
        repeat: true;
        onTriggered: {                
             blanker.prevent(1);
        }
}    

And done, your app will stay on as long as your app is on foreground. And do remember to call prevent(0) when you are done.



Ei kommentteja:

Lähetä kommentti