Using an XBOX 360 Controller on Android

I’ve been working on a few Android games in my spare time. With the rollout of Honeycomb to my Logitech Revue, I’ve been able to finally test these games on it. One of the things I noticed was that the Revue has USB Host support and (wired) Xbox 360 controllers are simply plug and play. Using them is quite simple as well; the button presses are mostly mapped to the key event. The left and right triggers, right directional stick, and analog inputs are not mapped through this method however. The left analog stick and directional pads have their inputs mapped to direction buttons.

[sourcecode language=”java”]
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_BUTTON_L1:
case KeyEvent.KEYCODE_BUTTON_R1:
case KeyEvent.KEYCODE_BUTTON_THUMBR:
case KeyEvent.KEYCODE_BUTTON_THUMBL:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_BUTTON_START:
case KeyEvent.KEYCODE_BUTTON_MODE://Big button in the middle
case KeyEvent.KEYCODE_BUTTON_B:
case KeyEvent.KEYCODE_BUTTON_A:
case KeyEvent.KEYCODE_BUTTON_X:
case KeyEvent.KEYCODE_BUTTON_Y:
default:
return super.onKeyDown(keyCode, keyEvent);
}
}
[/sourcecode]

Of special note, KeyEvent.KEYCODE_BUTTON_B goes back and KeyEvent.KEYCODE_BUTTON_START pulls up home bar in the default implementation. Also, the “A” button has special behaviors which I don’t fully understand.

For the analog controls however, we must override the method onGenericMotionEvent as follows:

[sourcecode language=”java”]
@Override
public boolean onGenericMotionEvent(MotionEvent event) {

Log.d("Right Trigger Value", event.getAxisValue(MotionEvent.AXIS_RTRIGGER) + "");
Log.d("Left Trigger Value", event.getAxisValue(MotionEvent.AXIS_LTRIGGER) + "");

Log.d("Left Stick X", event.getX() + "");
Log.d("Left Stick Y", event.getY() + "");

Log.d("Right Stick Y", event.getAxisValue(MotionEvent.AXIS_RZ) + "");
Log.d("Right Stick X", event.getAxisValue(MotionEvent.AXIS_Z) + "");

return super.onGenericMotionEvent(event);
}
[/sourcecode]

One Reply to “Using an XBOX 360 Controller on Android”

Leave a Reply

Your email address will not be published. Required fields are marked *