How to save screen in Qt for Android?

I've found a couple of solutions on how to do this in Java, but haven't found how to do it in QML or Qt. I know that first I have to set the permission WAKE_LOCK

to AndroidManifest.xml

. What should I do to enable and disable the screen lock from Qt at runtime?

+3


source to share


3 answers


You can use Qt Android Extras module and use JNI to call the corresponding Java function from C ++. Something like:



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);
        }
    }
}

      

+6


source


  • Use window.callMethod<void>

    insteadwindow.callObjectMethod

  • Launching on a GUI thread with QtAndroid::runOnAndroidThread

  • Clear exceptions after
  • To always disable a behavior use clearFlags

This is the tested Qt 5.7 code:



void keep_screen_on(bool on) {
  QtAndroid::runOnAndroidThread([on]{
    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;
        if (on) {
          window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
        } else {
          window.callMethod<void>("clearFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
        }
      }
    }
    QAndroidJniEnvironment env;
    if (env->ExceptionCheck()) {
      env->ExceptionClear();
    }
  });
}

      

+4


source


This can be done by editing the java file used by qt itself. In the installation path under src in the android path, you will find a QtActivity.java file. In onCreate function add below line

getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

      

You also need to add WAKE_LOCK permission to AndroidManifest.xml.

Create a project, it will work fine.

+1


source







All Articles