[SOLVED] Keep Android 5 Screen On



  • Hi. I need to keep the Android device awake, because my app works processing data from the camera. I've found this code here:

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

    It works fine on Android 4.x, and using that flag is the recommended way by this article, but on Android 5 the app crashes. The code above is the only one I could find. Does anyone know what changed on Lollipop?

    Thank you.



  • So, finally I could solve this. I'm documenting here the solution. Apparently, the crash has to do with some issue on JNI itself. I've seen some other topics unrelated to Qt with the same problem. In addition, Qt runs on another thread, so I wouldn't be able to easily call that "addFlags" method anyway. The solution was to extend QtActivity and keep the code on the Java side. Here's what I did:

    • Create a "src" folder inside "android" in the project tree

    • Create a "MyActivity.java" file inside "src"

      package com.example;
      public class MyActivity extends org.qtproject.qt5.android.bindings.QtActivity {
      	@Override
      	public void onCreate(android.os.Bundle savedInstanceState){
      		super.onCreate(savedInstanceState);
      		this.getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
      	}
      }
      
    • Edit the manifest

      <activity android:name="com.example.MyActivity" ...>


  • My code is identical to yours except for the code below. I have not seen any crash due to this code.

                <Same code as you here>
    
    	//Clear any possible pending exceptions.
    	QAndroidJniEnvironment env;
    	if (env->ExceptionCheck())
    	{
    		env->ExceptionClear();
    	}


  • Hi. Now that I understand JNI a little bit better, I've decided to give it a second chance. I'm using Qt 5.5.0 and Android 5.1.1. When I run the original code I first posted, I get:

    JNI DETECTED ERROR IN APPLICATION: the return type of CallObjectMethodV does not match void android.view.Window.addFlags(int) in call to CallObjectMethodV

    It makes sense, as I'm using callObjectMethod. So I change things a little:

    window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
    

    And to my surprise, it does work! I'm pretty sure I've tried it before, but I don't know why I couldn't get it to work. Maybe my lack of understanding on the topic back then was the main problem. Thank you for posting here. Now there are two solutions. Yet, extending QtActivity feels cleaner to me. I'll stick with it for now.


Log in to reply
 

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