Game Development Reference
In-Depth Information
public boolean
isKeyPressed(
int
keyCode) {
if
(keyCode<0 || keyCode>127)
return false
;
return
pressedKeys[keyCode];
}
The next method of our handler is the
isKeyPressed()
method, which implements the semantics
of
Input.isKeyPressed()
. First, we pass in an integer that specifies the key code (one of the
Android
KeyEvent.KEYCODE_XXX
constants) and returns whether that key is pressed or not. We
do this by looking up the state of the key in the
pressedKey
array after some range checking.
Remember, we set the elements of this array in the previous method, which gets called on the UI
thread. Since we are working with primitive types again, there's no need for synchronization.
public
List<KeyEvent>getKeyEvents() {
synchronized
(
this
) {
int
len=keyEvents.size();
for
(
int
i=0; i<len; i++) {
keyEventPool.free(keyEvents.get(i));
}
keyEvents.clear();
keyEvents.addAll(keyEventsBuffer);
keyEventsBuffer.clear();
return
keyEvents;
}
}
}
The last method of our handler is called
getKeyEvents()
, and it implements the semantics of the
Input.getKeyEvents()
method. Once again, we start with a synchronized block and remember
that this method will be called from a different thread.
Next, we loop through the
keyEvents
array and insert all of its
KeyEvent
s into our
Pool
.
Remember, we fetch instances from the
Pool
in the
onKey()
method on the UI thread. Here, we
reinsert them into the
Pool
. But isn't the
keyEvents
list empty? Yes, but only the first time we
invoke that method. To understand why, you have to grasp the rest of the method.
After our mysterious
Pool
insertion loop, we clear the
keyEvents
list and fill it with the events in
our
keyEventsBuffer
list. Finally, we clear the
keyEventsBuffer
list and return the newly filled
keyEvents
list to the caller. What is happening here?
We'll use a simple example to illustrate this. First, we'll examine what happens to the
keyEvents
and the
keyEventsBuffer
lists, as well as to our
Pool
, each time a new event arrives on the UI
thread or the game fetches the events in the main thread:
UI thread: onKey() ->
keyEvents={ }, keyEventsBuffer={KeyEvent1}, pool={ }
Main thread: getKeyEvents() ->
keyEvents={KeyEvent1}, keyEventsBuffer={ }, pool { }
UI thread: onKey() ->
keyEvents={KeyEvent1}, keyEventsBuffer={KeyEvent2}, pool { }