当前位置:  开发笔记 > 编程语言 > 正文

如何防止Android设备从Qt应用程序进入休眠状态

如何解决《如何防止Android设备从Qt应用程序进入休眠状态》经验,为你挑选了1个好方法。

我正在Android上部署Qt应用程序,需要防止设备进入待机状态(否则,我的线程被中断,我的BLE连接也会丢失).

我在SO上发现:如何阻止Android设备以编程方式进入睡眠状态?

应该执行这个Java代码:

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

// screen and CPU will stay awake during this section

wl.release();

但是如何在我的Qt应用程序中实现它?



1> jpo38..:

QAndroidJniObject有助于从Qt执行Java代码.写它可能很难,当它不起作用时很难弄清楚出了什么问题....

以下是锁定PowerManager.WakeLock对象的解决方案(封装在辅助类中):

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

然后,只需:

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

注意:您需要确保在清单中设置了WAKE_LOCK权限才能使用此代码.

推荐阅读
小妖694_807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有