Android keep screen on



  • Hello, I want to keep my android tablet screen on always. I've tried these lines below, but it doesn't work. How can we do that with Qt 5.5.1?

    • If I lock tablet screen with button and then unlock screen with button, the codes work and tablet screen always on.
    • If I wait until screen off automaticly and then unlock screen with button, the codes work and tablet screen always on.
    • I tried with QTimer and seperated class and called the KeepScreenOn function every 5 secs, it didn't work, screen goes off.
    • The codes work with Qt 5.4.2.

    Any idea?

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QAndroidJniObject>
    #include <QtAndroid>
    #include <QtAndroidExtras/QAndroidJniObject>
    void KeepScreenOn()
    {
        QAndroidJniObject activity = QtAndroid::androidActivity();
        if (activity.isValid())
        {
            QAndroidJniObject window = activity.callObjectMethod("getWindow", "()Landroid/view/Window;");
            if (window.isValid())
            {
                const int FLAG_KEEP_SCREEN_ON = 128;
                //window.callObjectMethod("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON); // Method 1
                window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON); // Method 2
            }
        }
    }
    
    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        KeepScreenOn();
        return app.exec();
    }


  • Same problem for me. Is this a bug? Are you sure it works for Qt 5.4.2?



  • You can do this with Androidmanifet.xml



  • I solved the problem.
    It seems that the only way to make it work is to extend the QtActivity.java class and add two methods that will be called from c++ using jni.

    This is the java code:

    public void disableIdleTimer()
    {
        this.runOnUiThread(new Runnable()
        {
            public void run()
            {
                Log.w(QtApplication.QtTAG, "UIActivity::disableIdleTimer");
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }
        } );
    }
    
    public void enableIdleTimer()
    {
        this.runOnUiThread(new Runnable()
        {
            public void run()
            {
                Log.w(QtApplication.QtTAG, "UIActivity::enableIdleTimer");
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }
        } );
    }


  • Yes, definitely it was work with Qt 5.4.2. In fact, I solved it on Java side.
    https://forum.qt.io/topic/57625/solved-keep-android-5-screen-on/2

    But it does not work with QAndroidJniObject.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.