How do I prevent an Android device from going to sleep from Qt application

后端 未结 2 1646
故里飘歌
故里飘歌 2021-01-05 17:21

I\'m deploying a Qt application on Android and need to prevent the device from going to standby (else, my threads are interrupted and also my BLE connection gets lost).

2条回答
  •  攒了一身酷
    2021-01-05 18:03

    QAndroidJniObject helps executing Java code from Qt. Writting it could be hard and it's hard to figure out what's wrong when it does not work....

    Here is the solution (encapsulated in a helper class) to lock a PowerManager.WakeLock object:

    LockHelper.h:

    #pragma once
    #include 
    
    class KeepAwakeHelper
    {
    public:
        KeepAwakeHelper();
        virtual ~KeepAwakeHelper();
    
    private:
        QAndroidJniObject m_wakeLock;
    };
    

    LockHelper.cpp:

    #include "LockHelper.h"
    #include 
    #include 
    #include "jni.h"
    
    KeepAwakeHelper::KeepAwakeHelper()
    {
        QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
        if ( activity.isValid() )
        {
            QAndroidJniObject serviceName = QAndroidJniObject::getStaticObjectField("android/content/Context","POWER_SERVICE");
            if ( serviceName.isValid() )
            {
                QAndroidJniObject powerMgr = activity.callObjectMethod("getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;",serviceName.object());
                if ( powerMgr.isValid() )
                {
                    jint levelAndFlags = QAndroidJniObject::getStaticField("android/os/PowerManager","SCREEN_DIM_WAKE_LOCK");
    
                    QAndroidJniObject tag = QAndroidJniObject::fromString( "My Tag" );
    
                    m_wakeLock = powerMgr.callObjectMethod("newWakeLock", "(ILjava/lang/String;)Landroid/os/PowerManager$WakeLock;", levelAndFlags,tag.object());
                }
            }
        }
    
        if ( m_wakeLock.isValid() )
        {
            m_wakeLock.callMethod("acquire", "()V");
            qDebug() << "Locked device, can't go to standby anymore";
        }
        else
        {
            assert( false );
        }
    }
    
    KeepAwakeHelper::~KeepAwakeHelper()
    {
        if ( m_wakeLock.isValid() )
        {
            m_wakeLock.callMethod("release", "()V");
            qDebug() << "Unlocked device, can now go to standby";
        }
    }
    

    Then, simply do:

    {
        KeepAwakeHelper helper;
        // screen and CPU will stay awake during this section
        // lock will be released when helper object goes out of scope
    }
    

    Note: You need to be sure you have the WAKE_LOCK permission set in your manifest in order to use this code.

提交回复
热议问题