From 239fd5791ed4ab33a6327b505f6b2ccf1ec07b7e Mon Sep 17 00:00:00 2001 From: Guilherme Gibertoni Date: Tue, 28 Aug 2018 16:54:36 -0300 Subject: [PATCH] When the game is active but there is another application on foreground If the device is locked or sleeps Then the application that was running on foreground will be dismissed and trigger a onWindowsFocusChanged(true) event while the game is already on background --- .../org/cocos2dx/lib/Cocos2dxActivity.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index 623f9e19e1ed..77c29fcceb18 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -25,6 +25,7 @@ of this software and associated documentation files (the "Software"), to deal package org.cocos2dx.lib; import android.app.Activity; +import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; @@ -35,6 +36,7 @@ of this software and associated documentation files (the "Software"), to deal import android.os.Build; import android.os.Bundle; import android.os.Message; +import android.os.PowerManager; import android.preference.PreferenceManager.OnActivityResultListener; import android.util.Log; import android.view.View; @@ -202,7 +204,11 @@ public void onWindowFocusChanged(boolean hasFocus) { } private void resumeIfHasFocus() { - if(hasFocus) { + //It is possible for the app to receive the onWindowsFocusChanged(true) event + //even though it is locked or asleep + boolean readyToPlay = !isDeviceLocked() && !isDeviceAsleep(); + + if(hasFocus && readyToPlay) { this.hideVirtualButton(); Cocos2dxHelper.onResume(); mGLSurfaceView.onResume(); @@ -358,6 +364,24 @@ private static boolean isAndroidEmulator() { return isEmulator; } + private static boolean isDeviceLocked() { + KeyguardManager keyguardManager = (KeyguardManager)getContext().getSystemService(Context.KEYGUARD_SERVICE); + boolean locked = keyguardManager.inKeyguardRestrictedInputMode(); + return locked; + } + + private static boolean isDeviceAsleep() { + PowerManager powerManager = (PowerManager)getContext().getSystemService(Context.POWER_SERVICE); + if(powerManager == null) { + return false; + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { + return !powerManager.isInteractive(); + } else { + return !powerManager.isScreenOn(); + } + } + // =========================================================== // Inner and Anonymous Classes // ===========================================================