Search code examples
androidc++qtscreensaver

How to disable screensaver on Qt Android App


I am using Qt on Android and I would like to disable the screen turning off / screensaver turning on.

I am not using QtQuick / QML, only C++. The Qt version is 5.8

edit: I forgot to mention that I use Qt Creator.


Solution

  • Actual source

    You need to add "QT += androidextras" to the .pro file

    #include <QtAndroidExtras/QAndroidJniEnvironment>
    #include <QtAndroidExtras/QtAndroidExtras>
    
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
    if (activity.isValid()) {
        QAndroidJniObject window = activity.callObjectMethod("getWindow", "()Landroid/view/Window;");
        if (window.isValid()) {
            const int FLAG_KEEP_SCREEN_ON = 128;
            window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
        }
    }
    
    //Clear any possible pending exceptions.
    QAndroidJniEnvironment env;
    if (env->ExceptionCheck()) {
        env->ExceptionClear();
    }