Game Development Reference
In-Depth Information
Cascading Key Events
Cascading key events from Android to a native engine involves these steps:
1.
Listening for key presses or releases from the Android activity.
2.
Translating the Android keys to ASCII (or whatever format the engine
uses to encode keys).
Calling the native methods keyPress or keyRelease for presses and
releases, respectively.
3.
Note that Android uses its own format to encode key values; thus the tricky part is to
translate the Android key codes to a format understood by the engine (ASCII is the format
for most portable engines). Listing 2-6 shows a simple way of doing this. You start by
defining two Java native methods: keyPress and keyRelease in the Android activity. Both
take an ASCII code as the argument.
When the user presses/releases a key on the device, Android fires the events onKeyDown
and onKeyUp , respectively. These events receive an Android key value and a KeyEvent
containing detailed information about the event. You then use the Android built-in function
queueEvent to queue a runnable to be run on the GL rendering thread. This can be used to
communicate with the renderer on the rendering thread in the game engine. The function
keyCodeToASCIICode is used to translate the Android key code to a portable ASCII code.
Finally, the native engine must implement the Java methods keyPress/keyRelease as Java
_keyPress and Java _keyPress , respectively. These methods will receive the ASCII code and
push it to the event queue (in this case, the event queue for the Quake engine).
Listing 2-6. Cascading Keys from Java to C
// In Java
public static native int keyPress(int key);
public static native int keyRelease(int key);
public boolean onKeyDown(final int keyCode, final KeyEvent event)
{
queueEvent(new Runnable() {
public void run() {
keyPress(keyCodeToASCIICode(keyCode));
}
});
return true;
}
public boolean onKeyUp(final int keyCode, final KeyEvent event)
{
queueEvent(new Runnable() {
public void run() {
keyRelease(keyCodeToASCIICode(keyCode));
}
});
return true;
}
 
Search WWH ::




Custom Search