简体   繁体   English

如何在Qt中为Android保持屏幕?

[英]How to keep the screen on in Qt for android?

I found a couple of solutions how to do that in Java, but did not find how can I do it in QML or Qt. 我在Java中找到了几个解决方法,但是我没有找到如何在QML或Qt中完成它。 I know that first I should set the WAKE_LOCK permission in AndroidManifest.xml . 我知道首先我应该在AndroidManifest.xml设置WAKE_LOCK权限。 What should I do to make it possible to turn on and off the screen locking from Qt in runtime? 我该怎么做才能在运行时打开和关闭Qt的屏幕锁定?

You can use the Qt Android Extras module and use JNI to call the relevant Java function from C++. 您可以使用Qt Android Extras模块并使用JNI从C ++调用相关的Java函数。 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);
        }
    }
}
  1. Use window.callMethod<void> instead of window.callObjectMethod 使用window.callMethod<void>而不是window.callObjectMethod
  2. Run on GUI thread with QtAndroid::runOnAndroidThread 使用QtAndroid::runOnAndroidThread在GUI线程上运行
  3. Clear exceptions afterwards 之后明确例外情况
  4. To disable always on behaviour, use clearFlags 要禁用始终开启的行为,请使用clearFlags

This is tested Qt 5.7 code: 这是经过测试的Qt 5.7代码:

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

You can achieve this by editing the java file used by qt itself. 您可以通过编辑qt本身使用的java文件来实现此目的。 In installation path under src in android path you will find QtActivity.java file. 在android路径下的src下的安装路径中,您将找到QtActivity.java文件。 In the onCreate function add the below line 在onCreate函数中添加以下行

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

WAKE_LOCK permission in AndroidManifest.xml also should be added. 还应添加AndroidManifest.xml中的WAKE_LOCK权限。

Build the project, it will work fine. 建立项目,它将工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM