W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
編寫:heray1990 - 原文:http://developer.android.com/training/game-controllers/compatibility.html
如果我們正為游戲提供游戲控制器的支持,那么我們需要確保我們的游戲?qū)τ谶\行著不同 Android 版本的設(shè)備對控制器都有一致的響應(yīng)。這會使得我們的游戲擴大用戶群體,同時,我們的玩家可以享受即使他們切換或者升級 Android 設(shè)備的時候,都可以使用他們的控制器無縫對接的游戲體驗。
這節(jié)課展示了如何用向下兼容的方式使用 Android 4.1 或者更高版本中可用的 API,使我們的游戲運行在 Android 2.3 或者更高的設(shè)備上時,支持下面的功能:
這節(jié)課的例子是基于 ControllerSample.zip
提供的參考實現(xiàn)。這個示例介紹了如何實現(xiàn) InputManagerCompat
接口來支持不同的 Android 版本。我們必須使用 Android 4.1(API level 16)或者更高的版本來編譯這個示例代碼。一旦編譯完成,生成的示例 app 可以在任何運行著 Android 2.3(API level 9)或者更高版本的設(shè)備上運行。
假設(shè)我們想確定在運行著 Android 2.3(API level 9)的設(shè)備上,游戲控制器的連接狀態(tài)是否發(fā)生改變。無論如何,API 只在 Android 4.1(API level 16)或者更高的版本上可用,所以我們需要提供一個支持 Android 4.1(API level 16)或者更高版本的實現(xiàn)方法的同時,提供一個支持從 Android 2.3 到 Android 4.0 的回退機制。
為了幫助我們確定哪個功能需要這樣的回退機制,table 1 列出了 Android 2.3(API level 9)、3.1(API level 12)和 4.1(API level 16)之間,對于支持游戲控制器的不同之處。
Table 1. API 在不同 Android 版本間對游戲控制器支持的不同點
Controller Information | Controller API | API level 9 | API level 12 | API level 16 |
Device Identification | getInputDeviceIds() | |||
getInputDevice() | ||||
getVibrator() | ||||
SOURCE_JOYSTICK | ||||
SOURCE_GAMEPAD | ||||
Connection Status | onInputDeviceAdded() | |||
onInputDeviceChanged() | ||||
onInputDeviceRemoved() | ||||
Input Event Identification | D-pad press ( KEYCODE_DPAD_UP, KEYCODE_DPAD_DOWN, KEYCODE_DPAD_LEFT, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_CENTER) | |||
Gamepad button press ( BUTTON_A, BUTTON_B, BUTTON_THUMBL, BUTTON_THUMBR, BUTTON_SELECT, BUTTON_START, BUTTON_R1, BUTTON_L1, BUTTON_R2, BUTTON_L2) | ||||
Joystick and hat switch movement ( AXIS_X, AXIS_Y, AXIS_Z, AXIS_RZ, AXIS_HAT_X, AXIS_HAT_Y) | ||||
Analog trigger press ( AXIS_LTRIGGER, AXIS_RTRIGGER) | * |
我們可以使用抽象化概念來建立能夠工作在不同平臺的版本識別的游戲控制器支持。這種方法包括下面幾個步驟:
定義一個中間 Java 接口來抽象化我們游戲需要的游戲控制器功能的實現(xiàn)。
創(chuàng)建一個使用 Android 4.1 和更高版本 API 的接口的代理實現(xiàn)。
創(chuàng)建一個使用 Android 2.3 到 Android 4.0 之間可用的 API 的接口的自定義實現(xiàn)。
創(chuàng)建在運行時,在這上述這些實現(xiàn)之間切換的邏輯,并且開始使用我們游戲中的接口。
有關(guān)如何使用抽象化概念來保證應(yīng)用可以在不同版本的 Android 之間,以向后兼容的方式工作的概述,請見創(chuàng)建向后兼容的 UI。
對于向后兼容,我們可以創(chuàng)建一個自定義接口,然后添加特定版本的實現(xiàn)。這種方法的一個優(yōu)點是它可以讓我們借鑒 Android 4.1(API level 16)上支持游戲控制器的公共接口。
// The InputManagerCompat interface is a reference example.
// The full code is provided in the ControllerSample.zip sample.
public interface InputManagerCompat {
...
public InputDevice getInputDevice(int id);
public int[] getInputDeviceIds();
public void registerInputDeviceListener(
InputManagerCompat.InputDeviceListener listener,
Handler handler);
public void unregisterInputDeviceListener(
InputManagerCompat.InputDeviceListener listener);
public void onGenericMotionEvent(MotionEvent event);
public void onPause();
public void onResume();
public interface InputDeviceListener {
void onInputDeviceAdded(int deviceId);
void onInputDeviceChanged(int deviceId);
void onInputDeviceRemoved(int deviceId);
}
...
}
InputManagerCompat
接口提供了下面的方法:
getInputDevice()
借鑒 getInputDevice()。包括代表一個游戲控制器兼容性的 InputDevice 對象。
getInputDeviceIds()
借鑒getInputDeviceIds()。返回一個整型數(shù)組,每一個數(shù)組成員表示一個不同輸入設(shè)備的 ID。這對于想要構(gòu)建一個支持多玩家和檢測連接了多少個控制器的游戲是很有用的。
registerInputDeviceListener()
借鑒registerInputDeviceListener()。注冊一個監(jiān)聽器,當(dāng)一個新的設(shè)備添加、改變或者移除的時候,我們會收到通知。
unregisterInputDeviceListener()
借鑒unregisterInputDeviceListener()。注銷一個輸入設(shè)備監(jiān)聽器。
onGenericMotionEvent()
借鑒onGenericMotionEvent()。讓我們的游戲截取和處理 MotionEvent 對象和代表類似移動搖桿和按下模擬觸發(fā)器等事件的坐標值。
onPause()
當(dāng)主 activity 暫?;蛘弋?dāng)游戲不再聚焦時,停止輪詢游戲控制器事件。
onResume()
當(dāng)主 activity 恢復(fù)或者當(dāng)游戲開始和在前臺運行時,啟動輪詢游戲控制器事件。
InputDeviceListener
借鑒 InputManager.InputDeviceListener 接口。當(dāng)添加、改變或者移除游戲控制器時,會通知我們的游戲。
下一步,創(chuàng)建 InputManagerCompat
的實現(xiàn),使得可以在不同平臺版本間工作。如果我們的游戲運行在 Android 4.1 或者更高版本,調(diào)用 InputManagerCompat
方法,代理實現(xiàn)調(diào)用在 InputManager 中等效的方法。然而,如果我們的游戲運行在 Andoird 2.3 到 Android 4.0,自定義的實現(xiàn)過程通過使用不晚于 Android 2.3 引進的 API 來調(diào)用 InputManagerCompat
方法。不管在運行時使用哪種特定版本的實現(xiàn),實現(xiàn)會透明地將回調(diào)結(jié)果傳給游戲。
Figure 1. 接口和特定版本實現(xiàn)的類圖。
InputManagerCompatV16
是 InputManagerCompat
接口的實現(xiàn),該接口代理方法調(diào)用一個 InputManager 和 InputManager.InputDeviceListener。InputManager是從系統(tǒng) Context 得到。
// The InputManagerCompatV16 class is a reference implementation.
// The full code is provided in the ControllerSample.zip sample.
public class InputManagerV16 implements InputManagerCompat {
private final InputManager mInputManager;
private final Map mListeners;
public InputManagerV16(Context context) {
mInputManager = (InputManager)
context.getSystemService(Context.INPUT_SERVICE);
mListeners = new HashMap();
}
@Override
public InputDevice getInputDevice(int id) {
return mInputManager.getInputDevice(id);
}
@Override
public int[] getInputDeviceIds() {
return mInputManager.getInputDeviceIds();
}
static class V16InputDeviceListener implements
InputManager.InputDeviceListener {
final InputManagerCompat.InputDeviceListener mIDL;
public V16InputDeviceListener(InputDeviceListener idl) {
mIDL = idl;
}
@Override
public void onInputDeviceAdded(int deviceId) {
mIDL.onInputDeviceAdded(deviceId);
}
// Do the same for device change and removal
...
}
@Override
public void registerInputDeviceListener(InputDeviceListener listener,
Handler handler) {
V16InputDeviceListener v16Listener = new
V16InputDeviceListener(listener);
mInputManager.registerInputDeviceListener(v16Listener, handler);
mListeners.put(listener, v16Listener);
}
// Do the same for unregistering an input device listener
...
@Override
public void onGenericMotionEvent(MotionEvent event) {
// unused in V16
}
@Override
public void onPause() {
// unused in V16
}
@Override
public void onResume() {
// unused in V16
}
}
InputManagerV9
實現(xiàn)使用了不晚于 Android 2.3 引進的 API。為了創(chuàng)建一個支持 Android 2.3 到 Android 4.0 的 InputManagerCompat
實現(xiàn),我們可以使用下面的對象:
SparseArray
跟蹤已連接到設(shè)備的游戲控制器。Handler
來處理設(shè)備事件。當(dāng)一個 app 啟動或者恢復(fù)時,Handler
接收一個消息來開始輪詢游戲控制器的斷開。Handler
將啟動一個循環(huán)來檢查每個已知連接的游戲控制器并且查看是否返回一個設(shè)備 ID。返回 null
表示游戲控制器斷開。當(dāng) app 暫停時,Handler
停止輪詢。InputManagerCompat.InputDeviceListener
的 Map
對象。我們會使用這個 listener 來更新跟蹤游戲遙控器的連接狀態(tài)。// The InputManagerCompatV9 class is a reference implementation.
// The full code is provided in the ControllerSample.zip sample.
public class InputManagerV9 implements InputManagerCompat {
private final SparseArray mDevices;
private final Map mListeners;
private final Handler mDefaultHandler;
…
public InputManagerV9() {
mDevices = new SparseArray();
mListeners = new HashMap();
mDefaultHandler = new PollingMessageHandler(this);
}
}
實現(xiàn)繼承 Handler
的 PollingMessageHandler
,并重寫 handleMessage()
方法。這個方法檢查已連接的游戲控制器是否已經(jīng)斷開并且通知已注冊的 listener。
private static class PollingMessageHandler extends Handler {
private final WeakReference mInputManager;
PollingMessageHandler(InputManagerV9 im) {
mInputManager = new WeakReference(im);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MESSAGE_TEST_FOR_DISCONNECT:
InputManagerV9 imv = mInputManager.get();
if (null != imv) {
long time = SystemClock.elapsedRealtime();
int size = imv.mDevices.size();
for (int i = 0; i < size; i++) {
long[] lastContact = imv.mDevices.valueAt(i);
if (null != lastContact) {
if (time - lastContact[0] > CHECK_ELAPSED_TIME) {
// check to see if the device has been
// disconnected
int id = imv.mDevices.keyAt(i);
if (null == InputDevice.getDevice(id)) {
// Notify the registered listeners
// that the game controller is disconnected
...
imv.mDevices.remove(id);
} else {
lastContact[0] = time;
}
}
}
}
sendEmptyMessageDelayed(MESSAGE_TEST_FOR_DISCONNECT,
CHECK_ELAPSED_TIME);
}
break;
}
}
}
至于啟動和停止輪詢游戲控制器的斷開,重寫這些方法:
private static final int MESSAGE_TEST_FOR_DISCONNECT = 101;
private static final long CHECK_ELAPSED_TIME = 3000L;
@Override
public void onPause() {
mDefaultHandler.removeMessages(MESSAGE_TEST_FOR_DISCONNECT);
}
@Override
public void onResume() {
mDefaultHandler.sendEmptyMessageDelayed(MESSAGE_TEST_FOR_DISCONNECT,
CHECK_ELAPSED_TIME);
}
重寫 onGenericMotionEvent()
方法檢測輸入設(shè)備是否已添加。當(dāng)系統(tǒng)通知一個動作事件時,檢查這個事件是否從已經(jīng)跟蹤過的還是新的設(shè)備 ID 中發(fā)出。如果是新的設(shè)備 ID,通知已注冊的 listener。
@Override
public void onGenericMotionEvent(MotionEvent event) {
// detect new devices
int id = event.getDeviceId();
long[] timeArray = mDevices.get(id);
if (null == timeArray) {
// Notify the registered listeners that a game controller is added
...
timeArray = new long[1];
mDevices.put(id, timeArray);
}
long time = SystemClock.elapsedRealtime();
timeArray[0] = time;
}
listener 的通知通過使用 Handler
對象發(fā)送一個 DeviceEvent
Runnable
對象到消息隊列來實現(xiàn)。DeviceEvent
包含了一個 InputManagerCompat.InputDeviceListener
的引用。當(dāng) DeviceEvent
運行時,適當(dāng)?shù)?listener 回調(diào)方法會被調(diào)用,標志游戲控制器是否被添加、改變或者移除。
@Override
public void registerInputDeviceListener(InputDeviceListener listener,
Handler handler) {
mListeners.remove(listener);
if (handler == null) {
handler = mDefaultHandler;
}
mListeners.put(listener, handler);
}
@Override
public void unregisterInputDeviceListener(InputDeviceListener listener) {
mListeners.remove(listener);
}
private void notifyListeners(int why, int deviceId) {
// the state of some device has changed
if (!mListeners.isEmpty()) {
for (InputDeviceListener listener : mListeners.keySet()) {
Handler handler = mListeners.get(listener);
DeviceEvent odc = DeviceEvent.getDeviceEvent(why, deviceId,
listener);
handler.post(odc);
}
}
}
private static class DeviceEvent implements Runnable {
private int mMessageType;
private int mId;
private InputDeviceListener mListener;
private static Queue sObjectQueue =
new ArrayDeque();
...
static DeviceEvent getDeviceEvent(int messageType, int id,
InputDeviceListener listener) {
DeviceEvent curChanged = sObjectQueue.poll();
if (null == curChanged) {
curChanged = new DeviceEvent();
}
curChanged.mMessageType = messageType;
curChanged.mId = id;
curChanged.mListener = listener;
return curChanged;
}
@Override
public void run() {
switch (mMessageType) {
case ON_DEVICE_ADDED:
mListener.onInputDeviceAdded(mId);
break;
case ON_DEVICE_CHANGED:
mListener.onInputDeviceChanged(mId);
break;
case ON_DEVICE_REMOVED:
mListener.onInputDeviceRemoved(mId);
break;
default:
// Handle unknown message type
...
break;
}
// Put this runnable back in the queue
sObjectQueue.offer(this);
}
}
我們現(xiàn)在已經(jīng)有兩個 InputManagerCompat
的實現(xiàn):一個可以在運行 Android 4.1 或者更高版本的設(shè)備上工作,另一個可以在運行 Android 2.3 到 Android 4.0 的設(shè)備上工作。
特定版本切換的邏輯是在一個充當(dāng) factory 的類中實現(xiàn)。
public static class Factory {
public static InputManagerCompat getInputManager(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return new InputManagerV16(context);
} else {
return new InputManagerV9();
}
}
}
現(xiàn)在我們可以簡單地實例化一個 InputManagerCompat
對象,并且在主 View
中注冊 InputManagerCompat.InputDeviceListener
。由于我們建立的版本切換邏輯,我們的游戲會自動為設(shè)備上運行的 Android 版本使用適當(dāng)?shù)膶崿F(xiàn)。
public class GameView extends View implements InputDeviceListener {
private InputManagerCompat mInputManager;
...
public GameView(Context context, AttributeSet attrs) {
mInputManager =
InputManagerCompat.Factory.getInputManager(this.getContext());
mInputManager.registerInputDeviceListener(this, null);
...
}
}
下一步,重寫主 View 的 onGenericMotionEvent()
方法,詳見處理從游戲控制器傳來的 MotionEvent。我們的游戲現(xiàn)在應(yīng)該可以一致地處理運行著 Android 2.3(API level 9)和更高版本設(shè)備上的游戲控制器事件。
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
mInputManager.onGenericMotionEvent(event);
// Handle analog input from the controller as normal
...
return super.onGenericMotionEvent(event);
}
我們可以在上述的 ControllerSample.zip
示例的 GameView
類中找到這個兼容性的完整的代碼。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: