我正在开发应用程序来检查哪些必须连接到 MQTT 服务器才能从服务器获取消息。当 android 设备进入打盹模式时,客户端(Android)会自动断开连接,因为网络已暂停但处于活动状态。
一旦设备进入打盹模式,我需要唤醒我的设备,连接到使用 MQTT 的服务器
我已经为此编写了代码,我需要确保我是否在正确的轨道上?
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isIdle = pm.isDeviceIdleMode();
Log.d(TAG, " --- DozeModeReceiver isIdle--- "+isIdle);
if (isIdle) {
// the device is now in doze mode
if (screenWakeLock == null) {
PowerManager mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
screenWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyWakeLockTag");
Log.d(TAG, " --- Going to Wake Screen ... --- " + result);
screenWakeLock.acquire();
try {
/**
*Code to connect with MQTT Server
*/
} catch (Exception e) {
e.printStackTrace();
}
}
if (screenWakeLock != null) {
screenWakeLock.release();
Log.i(TAG, "screenWakeLock Released ");
}
} else {
// the device just woke up from doze mode
Log.d(TAG, " --- Woke up from Doze mode --- "+isIdle);
}}