我正在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应用程序中实现它?
QAndroidJniObject有助于从Qt执行Java代码.写它可能很难,当它不起作用时很难弄清楚出了什么问题....
以下是锁定PowerManager.WakeLock
对象的解决方案(封装在辅助类中):
LockHelper.h:
#pragma once #includeclass 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权限才能使用此代码.