Game Development Reference
In-Depth Information
AndroidInput: The Great Coordinator
The Input implementation of our game framework ties together all the handlers we have
developed. Any method calls are delegated to the corresponding handler. The only interesting
part of this implementation is choosing which TouchHandler implementation to use, based
on the Android version the device is running. Listing 5-12 shows an implementation called
AndroidInput , with commentary.
Listing 5-12. AndroidInput.java; Handling the Handlers with Style
package com.badlogic.androidgames.framework.impl;
import java.util.List;
import android.content.Context;
import android.os.Build.VERSION;
import android.view.View;
import com.badlogic.androidgames.framework.Input;
public class AndroidInput implements Input {
AccelerometerHandler accelHandler;
KeyboardHandler keyHandler;
TouchHandler touchHandler;
We start by letting the class implement the Input interface defined in Chapter 3. This leads us to
three members: an AccelerometerHandler , a KeyboardHandler , and a TouchHandler .
public AndroidInput(Context context, View view, float scaleX, float scaleY) {
accelHandler= new AccelerometerHandler(context);
keyHandler= new KeyboardHandler(view);
if (Integer. parseInt (VERSION. SDK )<5)
touchHandler= new SingleTouchHandler(view, scaleX, scaleY);
else
touchHandler= new MultiTouchHandler(view, scaleX, scaleY);
}
These members are initialized in the constructor, which takes a Context , a View , and the scaleX
and scaleY parameters, which we can ignore again. The AccelerometerHandler is instantiated
via the Context parameter, as the KeyboardHandler needs the View that is passed in.
To decide which TouchHandler to use, we simply check the Android version that the application
uses to run. This can be done using the VERSION.SDK string, which is a constant provided by the
Android API. It is unclear why this is a string, since it directly encodes the SDK version numbers
we use in our manifest file. Therefore, we need to make it into an integer in order to do some
comparisons. The first Android version to support the multitouch API was version 2.0, which
corresponds to SDK version 5. If the current device runs a lower Android version, we instantiate
the SingleTouchHandler ; otherwise, we use the MultiTouchHandler . At an API level, this is all the
fragmentation we need to care about. When we start rendering OpenGL, we'll hit a few more
fragmentation issues, but there is no need to worry—they are easily resolved, just like the touch
API problems.
 
Search WWH ::




Custom Search