19
19
*/
20
20
public class GameMenu {
21
21
22
+ private static final long TEST_GAME_FOCUS_DELAY = 10 ;
22
23
private static final long KEY_UP_DELAY = 25 ;
23
24
24
25
public static class MenuOption {
25
26
private final String label ;
27
+ private final boolean withGameFocus ;
26
28
private final Runnable runnable ;
27
29
28
- public MenuOption (String label , Runnable runnable ) {
30
+ public MenuOption (String label , boolean withGameFocus , Runnable runnable ) {
29
31
this .label = label ;
32
+ this .withGameFocus = withGameFocus ;
30
33
this .runnable = runnable ;
31
34
}
35
+
36
+ public MenuOption (String label , Runnable runnable ) {
37
+ this (label , false , runnable );
38
+ }
32
39
}
33
40
34
41
private final Game game ;
@@ -85,6 +92,32 @@ private void sendKeys(short[] keys) {
85
92
}), KEY_UP_DELAY );
86
93
}
87
94
95
+ private void runWithGameFocus (Runnable runnable ) {
96
+ // Ensure that the Game activity is still active (not finished)
97
+ if (game .isFinishing ()) {
98
+ return ;
99
+ }
100
+ // Check if the game window has focus again, if not try again after delay
101
+ if (!game .hasWindowFocus ()) {
102
+ new Handler ().postDelayed (() -> runWithGameFocus (runnable ), TEST_GAME_FOCUS_DELAY );
103
+ return ;
104
+ }
105
+ // Game Activity has focus, run runnable
106
+ runnable .run ();
107
+ }
108
+
109
+ private void run (MenuOption option ) {
110
+ if (option .runnable == null ) {
111
+ return ;
112
+ }
113
+
114
+ if (option .withGameFocus ) {
115
+ runWithGameFocus (option .runnable );
116
+ } else {
117
+ option .runnable .run ();
118
+ }
119
+ }
120
+
88
121
private void showMenuDialog (String title , MenuOption [] options ) {
89
122
AlertDialog .Builder builder = new AlertDialog .Builder (game );
90
123
builder .setTitle (title );
@@ -103,9 +136,7 @@ private void showMenuDialog(String title, MenuOption[] options) {
103
136
continue ;
104
137
}
105
138
106
- if (option .runnable != null ) {
107
- option .runnable .run ();
108
- }
139
+ run (option );
109
140
break ;
110
141
}
111
142
});
@@ -136,7 +167,7 @@ private void showSpecialKeysMenu() {
136
167
private void showMenu () {
137
168
List <MenuOption > options = new ArrayList <>();
138
169
139
- options .add (new MenuOption (getString (R .string .game_menu_toggle_keyboard ),
170
+ options .add (new MenuOption (getString (R .string .game_menu_toggle_keyboard ), true ,
140
171
() -> game .toggleKeyboard ()));
141
172
142
173
if (device != null ) {
0 commit comments