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. I know that first I should set the WAKE_LOCK
permission in AndroidManifest.xml
. What should I do to make it possible to turn on and off the screen locking from Qt in runtime?
Asked
Active
Viewed 4,303 times
8
3 Answers
13
- Use
window.callMethod<void>
instead ofwindow.callObjectMethod
- Run on GUI thread with
QtAndroid::runOnAndroidThread
- Clear exceptions afterwards
- To disable always on behaviour, use
clearFlags
This is 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();
}
});
}

psyched
- 1,859
- 1
- 21
- 28
9
You can use the Qt Android Extras module and use JNI to call the relevant 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);
}
}
}

Nejat
- 31,784
- 12
- 106
- 138
-
If I call it in main() it is working as expected, but if I call it in a slot it is not working and throwing some java exception. Is the QGuiApplication event loop moving to different thread after calling exec(). – Uga Buga Feb 22 '15 at 23:09
-
No. `QGuiApplication` would remain in the application main thread. May be it is better to ask it in a new new question and describe your problem. – Nejat Feb 23 '15 at 03:58
1
You can achieve this by editing the java file used by qt itself. In installation path under src in android path you will find QtActivity.java file. In the onCreate function add the below line
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WAKE_LOCK permission in AndroidManifest.xml also should be added.
Build the project, it will work fine.

A.J
- 725
- 10
- 33