How to save screen in Qt for Android?
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 to share
- 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 to share
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 to share