简体   繁体   中英

How to prevent android device from sleep while qt application is running

I have an android application of slideshow which is developed in qt. The device after some time, gets the screen dim, and goes off and locked. How can I avoid this, until user quits the application.

Like similar to “android.permission.WAKE_LOCK” and call some functions.. I'm not sure exactly.

You need to execute this piece of java code:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

To do so, add this file to your project:

WakeLock.java:

package my.utl;

import org.qtproject.qt5.android.bindings.QtActivity;
import org.qtproject.qt5.android.bindings.QtApplication;
import java.lang.String;
import android.app.Activity;
import android.os.PowerManager;
import android.content.Context;

public class WakeLock
{
    private Activity myActivity;
    protected PowerManager.WakeLock m_WakeLock = null;

    public WakeLock(Activity a)
    {
        myActivity = a;
    }

    public int configure()
    {
        System.out.println("Inside WakeLock::configure");

        try
        {
            final PowerManager pm = (PowerManager) myActivity.getSystemService(Context.POWER_SERVICE);

            m_WakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
            // m_WakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
            // Does not work: https://stackoverflow.com/questions/5183859/partial-wake-lock-vs-screen-dim-wake-lock-in-download-thread
            m_WakeLock.acquire();

            return 42;
        }
        catch (Exception e)
        {
            System.out.println("WakeLock failed: " + e.toString());
        }

        return -1;
    }
}

Then, from your app, just execute the code:

QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");    //activity is valid
if ( activity.isValid() )
{
    QAndroidJniObject wakeLockObject("my/utl/WakeLock","(Landroid/app/Activity;)V",activity.object<jobject>());
    if ( wakeLockObject.isValid() )
    {
        jint res = wakeLockObject.callMethod<jint>("configure","()I");
        assert( res == 42 ); // check Java code was executed...
    }
    else
    {
        assert( false );
    }
}
else
{
    assert( false );
}

There might be a way to do this without the java file. I'm working on it: Unable to call PowerManager.WakeLock.newWakeLock using QAndroidJniObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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