鍍金池/ 教程/ Android/ 在不同的 Android 系統(tǒng)版本支持控制器
檢測(cè)常用的手勢(shì)
優(yōu)化layout的層級(jí)
用戶輸入
管理應(yīng)用的內(nèi)存
聯(lián)系人信息
開發(fā)輔助程序
Android多媒體
添加語音功能
顯示位置地址
提供向下與橫向?qū)Ш?/span>
支持游戲控制器
訪問可穿戴數(shù)據(jù)層
處理多點(diǎn)觸控手勢(shì)
全屏沉浸式應(yīng)用
為多線程創(chuàng)建管理器
數(shù)據(jù)保存
Intent的發(fā)送
更新Notification
優(yōu)化下載以高效地訪問網(wǎng)絡(luò)
打印
打包可穿戴應(yīng)用
接收從其他App傳送來的數(shù)據(jù)
發(fā)送與接收消息
建立靈活動(dòng)態(tài)的UI
處理鍵盤輸入
Building a Work Policy Controller
建立測(cè)試環(huán)境
創(chuàng)建表盤
分享文件
顯示Notification進(jìn)度
實(shí)現(xiàn)自適應(yīng)UI流(Flows)
使用設(shè)備管理策略增強(qiáng)安全性
使用能感知版本的組件
執(zhí)行網(wǎng)絡(luò)操作
建立文件分享
添加移動(dòng)
更新你的Security Provider來對(duì)抗SSL漏洞利用
支持鍵盤導(dǎo)航
創(chuàng)建和監(jiān)視地理圍欄
發(fā)送并同步數(shù)據(jù)
使用BigView樣式
無線連接設(shè)備
提供向上導(dǎo)航與歷史導(dǎo)航
最小化定期更新造成的影響
實(shí)現(xiàn)向下的導(dǎo)航
支持不同的屏幕大小
Android 可穿戴應(yīng)用
添加動(dòng)畫
顯示聯(lián)系人頭像
使用OpenGL ES顯示圖像
處理輸入法可見性
分享文件
保持設(shè)備喚醒
淡化系統(tǒng)Bar
使用NFC分享文件
保存到Preference
Android聯(lián)系人信息與位置信息
創(chuàng)建標(biāo)準(zhǔn)的網(wǎng)絡(luò)請(qǐng)求
使用Drawables
管理Bitmap的內(nèi)存使用
管理Activity的生命周期
按需加載視圖
傳輸資源
為可穿戴設(shè)備創(chuàng)建自定義UI
在一個(gè)線程中執(zhí)行一段特定的代碼
性能優(yōu)化
隱藏導(dǎo)航欄
創(chuàng)建目錄瀏覽器
為多種大小的屏幕進(jìn)行規(guī)劃
View間漸變
使用觸摸手勢(shì)
高效加載大圖
使用CursorLoader在后臺(tái)加載數(shù)據(jù)
創(chuàng)建抽屜式導(dǎo)航(navigation drawer)
管理音頻焦點(diǎn)
創(chuàng)建后臺(tái)服務(wù)
創(chuàng)建功能測(cè)試
創(chuàng)建使用Material Design的應(yīng)用
停止與重啟Activity
添加一個(gè)簡(jiǎn)便的分享功能
啟動(dòng)Activity時(shí)保留導(dǎo)航
TV應(yīng)用清單
創(chuàng)建向后兼容的UI
?# 優(yōu)化自定義View
創(chuàng)建單元測(cè)試
在UI上顯示Bitmap
建立OpenGL ES的環(huán)境
構(gòu)建表盤服務(wù)
JNI Tips
建立搜索界面
實(shí)現(xiàn)自定義View的繪制
使用HTTPS與SSL
按需操控BroadcastReceiver
分享簡(jiǎn)單的數(shù)據(jù)
繪制形狀
Android位置信息
創(chuàng)建并運(yùn)行可穿戴應(yīng)用
執(zhí)行 Sync Adpater
獲取最后可知位置
創(chuàng)建 Android 項(xiàng)目
實(shí)現(xiàn)高效的導(dǎo)航
退出全屏的Activity
創(chuàng)建Card
兼容音頻輸出設(shè)備
同步數(shù)據(jù)單元
傳輸數(shù)據(jù)時(shí)避免消耗大量電量
保存到文件
緩存Bitmap
提供配置 Activity
調(diào)度重復(fù)的鬧鐘
實(shí)現(xiàn)輔助功能
重復(fù)的下載是冗余的
隱藏狀態(tài)欄
實(shí)現(xiàn)自定義的網(wǎng)絡(luò)請(qǐng)求
規(guī)劃界面和他們之間的關(guān)系
使用Sync Adapter傳輸數(shù)據(jù)
TV應(yīng)用內(nèi)搜索
響應(yīng)觸摸事件
使用Google Cloud Messaging(已廢棄)
控制相機(jī)
Android網(wǎng)絡(luò)連接與云服務(wù)
請(qǐng)求分享一個(gè)文件
處理TV硬件
響應(yīng)UI可見性的變化
使用網(wǎng)絡(luò)服務(wù)發(fā)現(xiàn)
指定輸入法類型
優(yōu)化電池壽命
創(chuàng)建TV應(yīng)用
獲取聯(lián)系人列表
拖拽與縮放
啟動(dòng)與停止線程池中的線程
創(chuàng)建 Sync Adpater
使用 WiFi P2P 服務(wù)發(fā)現(xiàn)
開始使用Material Design
代理至新的APIs
使用include標(biāo)簽重用layouts
使得View可交互
高效顯示Bitmap
創(chuàng)建企業(yè)級(jí)應(yīng)用
Fragments之間的交互
創(chuàng)建與執(zhí)行測(cè)試用例
綜合:設(shè)計(jì)我們的樣例 App
繪制表盤
建立簡(jiǎn)單的用戶界面
自定義動(dòng)畫
開發(fā)輔助服務(wù)
避免出現(xiàn)程序無響應(yīng)ANR(Keeping Your App Responsive)
使用ViewPager實(shí)現(xiàn)屏幕滑動(dòng)
設(shè)計(jì)高效的導(dǎo)航
Android分享操作(Building Apps with Content Sharing)
提供向后的導(dǎo)航
保持向下兼容
創(chuàng)建TV播放應(yīng)用
縮放View
使用 WiFi 建立 P2P 連接
Android后臺(tái)任務(wù)
連接到網(wǎng)絡(luò)
為 Notification 添加頁面
使TV應(yīng)用是可被搜索的
添加Action Bar
使用Material的主題
啟動(dòng)另一個(gè)Activity
顯示正在播放卡片
適配不同的系統(tǒng)版本
輕松錄制視頻
創(chuàng)建可穿戴的應(yīng)用
創(chuàng)建自定義的布局
重新創(chuàng)建Activity
使用CursorLoader執(zhí)行查詢?nèi)蝿?wù)
使用舊的APIs實(shí)現(xiàn)新API的效果
使用備份API
安全要點(diǎn)
Android入門基礎(chǔ):從這里開始
保存并搜索數(shù)據(jù)
根據(jù)網(wǎng)絡(luò)連接類型來調(diào)整下載模式
使用Tabs創(chuàng)建Swipe視圖
SMP(Symmetric Multi-Processor) Primer for Android
解析 XML 數(shù)據(jù)
使用 Volley 傳輸網(wǎng)絡(luò)數(shù)據(jù)
建立ActionBar
Android交互設(shè)計(jì)
使用Intent修改聯(lián)系人信息
增加搜索功能
輕松拍攝照片
定義形狀
測(cè)試你的Activity
在 Notifcation 中接收語音輸入
與其他應(yīng)用的交互
管理系統(tǒng)UI
追蹤手勢(shì)移動(dòng)
Android界面設(shè)計(jì)
執(zhí)行 Android 程序
顯示確認(rèn)界面
創(chuàng)建Lists與Cards
打印HTML文檔
創(chuàng)建TV應(yīng)用
為多屏幕設(shè)計(jì)
定義Shadows與Clipping視圖
使用Fragment建立動(dòng)態(tài)UI
接收Activity返回的結(jié)果
布局變更動(dòng)畫
定位常見的問題
自定義ActionBar的風(fēng)格
定義Layouts
發(fā)送簡(jiǎn)單的網(wǎng)絡(luò)請(qǐng)求
啟動(dòng)與銷毀Activity
與UI線程通信
非UI線程處理Bitmap
創(chuàng)建TV布局
提升Layout的性能
報(bào)告任務(wù)執(zhí)行狀態(tài)
判斷并監(jiān)測(cè)網(wǎng)絡(luò)連接狀態(tài)
兼容不同的設(shè)備
處理按鍵動(dòng)作
優(yōu)化性能和電池使用時(shí)間
給其他App發(fā)送簡(jiǎn)單的數(shù)據(jù)
Implementing App Restrictions
向后臺(tái)服務(wù)發(fā)送任務(wù)請(qǐng)求
展示Card翻轉(zhuǎn)動(dòng)畫
管理ViewGroup中的觸摸事件
兼容不同的屏幕密度
通過藍(lán)牙進(jìn)行調(diào)試
為可穿戴設(shè)備創(chuàng)建Notification
控制音量與音頻播放
獲取聯(lián)系人詳情
在表盤上顯示信息
提供向上的導(dǎo)航
滾動(dòng)手勢(shì)動(dòng)畫
幫助用戶在TV上找到內(nèi)容
創(chuàng)建TV導(dǎo)航
為索引指定App內(nèi)容
ActionBar的覆蓋疊加
Android Wear 上的位置檢測(cè)
保護(hù)安全與隱私的最佳策略
Ensuring Compatibility with Managed Profiles
解決云同步的保存沖突
獲取位置更新
創(chuàng)建List
測(cè)試程序
管理網(wǎng)絡(luò)的使用情況
為App內(nèi)容開啟深度鏈接
推薦TV內(nèi)容
建立一個(gè)Notification
管理音頻播放
設(shè)計(jì)表盤
拍照
處理控制器輸入動(dòng)作
判斷并監(jiān)測(cè)設(shè)備的底座狀態(tài)與類型
處理查詢的結(jié)果
保存到數(shù)據(jù)庫
支持多個(gè)游戲控制器
創(chuàng)建 Stub Content Provider
使得ListView滑動(dòng)順暢
處理數(shù)據(jù)層的事件
創(chuàng)建TV應(yīng)用的第一步
使得你的App內(nèi)容可被Google搜索
將 Notification 放成一疊
創(chuàng)建 Stub 授權(quán)器
暫停與恢復(fù)Activity
管理設(shè)備的喚醒狀態(tài)
Android圖像與動(dòng)畫
打印照片
云同步
創(chuàng)建TV直播應(yīng)用
為Notification賦加可穿戴特性
提供一個(gè)Card視圖
建立請(qǐng)求隊(duì)列(RequestQueue)
適配不同的語言
創(chuàng)建詳情頁
測(cè)試UI組件
接收其他設(shè)備的文件
創(chuàng)建自定義View
建立第一個(gè)App
創(chuàng)建2D Picker
監(jiān)測(cè)電池的電量與充電狀態(tài)
打印自定義文檔
抽象出新的APIs
通知提示用戶
獲取文件信息
運(yùn)用投影與相機(jī)視角
在IntentService中執(zhí)行后臺(tái)任務(wù)
多線程操作
創(chuàng)建一個(gè)Fragment
添加Action按鈕
在不同的 Android 系統(tǒng)版本支持控制器
維護(hù)兼容性
發(fā)送文件給其他設(shè)備
創(chuàng)建TV游戲應(yīng)用
創(chuàng)建自定義的View類
代碼性能優(yōu)化建議
Intent過濾
適配不同的屏幕

在不同的 Android 系統(tǒng)版本支持控制器

編寫:heray1990 - 原文:http://developer.android.com/training/game-controllers/compatibility.html

如果我們正為游戲提供游戲控制器的支持,那么我們需要確保我們的游戲?qū)τ谶\(yùn)行著不同 Android 版本的設(shè)備對(duì)控制器都有一致的響應(yīng)。這會(huì)使得我們的游戲擴(kuò)大用戶群體,同時(shí),我們的玩家可以享受即使他們切換或者升級(jí) Android 設(shè)備的時(shí)候,都可以使用他們的控制器無縫對(duì)接的游戲體驗(yàn)。

這節(jié)課展示了如何用向下兼容的方式使用 Android 4.1 或者更高版本中可用的 API,使我們的游戲運(yùn)行在 Android 2.3 或者更高的設(shè)備上時(shí),支持下面的功能:

  • 游戲可以檢測(cè)是否有一個(gè)新的游戲控制器接入、變更或者移除。
  • 游戲可以查詢游戲控制器的兼容性。
  • 游戲可以識(shí)別從游戲控制器傳入的動(dòng)作事件。

這節(jié)課的例子是基于 ControllerSample.zip 提供的參考實(shí)現(xiàn)。這個(gè)示例介紹了如何實(shí)現(xiàn) InputManagerCompat 接口來支持不同的 Android 版本。我們必須使用 Android 4.1(API level 16)或者更高的版本來編譯這個(gè)示例代碼。一旦編譯完成,生成的示例 app 可以在任何運(yùn)行著 Android 2.3(API level 9)或者更高版本的設(shè)備上運(yùn)行。

準(zhǔn)備支持游戲控制器的抽象 API

假設(shè)我們想確定在運(yùn)行著 Android 2.3(API level 9)的設(shè)備上,游戲控制器的連接狀態(tài)是否發(fā)生改變。無論如何,API 只在 Android 4.1(API level 16)或者更高的版本上可用,所以我們需要提供一個(gè)支持 Android 4.1(API level 16)或者更高版本的實(shí)現(xiàn)方法的同時(shí),提供一個(gè)支持從 Android 2.3 到 Android 4.0 的回退機(jī)制。

為了幫助我們確定哪個(gè)功能需要這樣的回退機(jī)制,table 1 列出了 Android 2.3(API level 9)、3.1(API level 12)和 4.1(API level 16)之間,對(duì)于支持游戲控制器的不同之處。

Table 1. API 在不同 Android 版本間對(duì)游戲控制器支持的不同點(diǎn)

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) * *

我們可以使用抽象化概念來建立能夠工作在不同平臺(tái)的版本識(shí)別的游戲控制器支持。這種方法包括下面幾個(gè)步驟:

  1. 定義一個(gè)中間 Java 接口來抽象化我們游戲需要的游戲控制器功能的實(shí)現(xiàn)。

  2. 創(chuàng)建一個(gè)使用 Android 4.1 和更高版本 API 的接口的代理實(shí)現(xiàn)。

  3. 創(chuàng)建一個(gè)使用 Android 2.3 到 Android 4.0 之間可用的 API 的接口的自定義實(shí)現(xiàn)。

  4. 創(chuàng)建在運(yùn)行時(shí),在這上述這些實(shí)現(xiàn)之間切換的邏輯,并且開始使用我們游戲中的接口。

有關(guān)如何使用抽象化概念來保證應(yīng)用可以在不同版本的 Android 之間,以向后兼容的方式工作的概述,請(qǐng)見創(chuàng)建向后兼容的 UI。

添加向后兼容的接口

對(duì)于向后兼容,我們可以創(chuàng)建一個(gè)自定義接口,然后添加特定版本的實(shí)現(xiàn)。這種方法的一個(gè)優(yōu)點(diǎn)是它可以讓我們借鑒 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()。包括代表一個(gè)游戲控制器兼容性的 InputDevice 對(duì)象。

getInputDeviceIds()

借鑒getInputDeviceIds()。返回一個(gè)整型數(shù)組,每一個(gè)數(shù)組成員表示一個(gè)不同輸入設(shè)備的 ID。這對(duì)于想要構(gòu)建一個(gè)支持多玩家和檢測(cè)連接了多少個(gè)控制器的游戲是很有用的。

registerInputDeviceListener()

借鑒registerInputDeviceListener()。注冊(cè)一個(gè)監(jiān)聽器,當(dāng)一個(gè)新的設(shè)備添加、改變或者移除的時(shí)候,我們會(huì)收到通知。

unregisterInputDeviceListener()

借鑒unregisterInputDeviceListener()。注銷一個(gè)輸入設(shè)備監(jiān)聽器。

onGenericMotionEvent()

借鑒onGenericMotionEvent()。讓我們的游戲截取和處理 MotionEvent 對(duì)象和代表類似移動(dòng)搖桿和按下模擬觸發(fā)器等事件的坐標(biāo)值。

onPause()

當(dāng)主 activity 暫停或者當(dāng)游戲不再聚焦時(shí),停止輪詢游戲控制器事件。

onResume()

當(dāng)主 activity 恢復(fù)或者當(dāng)游戲開始和在前臺(tái)運(yùn)行時(shí),啟動(dòng)輪詢游戲控制器事件。

InputDeviceListener

借鑒 InputManager.InputDeviceListener 接口。當(dāng)添加、改變或者移除游戲控制器時(shí),會(huì)通知我們的游戲。

下一步,創(chuàng)建 InputManagerCompat 的實(shí)現(xiàn),使得可以在不同平臺(tái)版本間工作。如果我們的游戲運(yùn)行在 Android 4.1 或者更高版本,調(diào)用 InputManagerCompat 方法,代理實(shí)現(xiàn)調(diào)用在 InputManager 中等效的方法。然而,如果我們的游戲運(yùn)行在 Andoird 2.3 到 Android 4.0,自定義的實(shí)現(xiàn)過程通過使用不晚于 Android 2.3 引進(jìn)的 API 來調(diào)用 InputManagerCompat 方法。不管在運(yùn)行時(shí)使用哪種特定版本的實(shí)現(xiàn),實(shí)現(xiàn)會(huì)透明地將回調(diào)結(jié)果傳給游戲。

http://wiki.jikexueyuan.com/project/android-training-geek/images/backward-compatible-inputmanager.png" alt="" />

Figure 1. 接口和特定版本實(shí)現(xiàn)的類圖。

實(shí)現(xiàn) Android 4.1 和更高版本的接口

InputManagerCompatV16InputManagerCompat 接口的實(shí)現(xiàn),該接口代理方法調(diào)用一個(gè) InputManagerInputManager.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
    }

}

實(shí)現(xiàn) Android 2.3 到 Android 4.0 的接口

InputManagerV9 實(shí)現(xiàn)使用了不晚于 Android 2.3 引進(jìn)的 API。為了創(chuàng)建一個(gè)支持 Android 2.3 到 Android 4.0 的 InputManagerCompat 實(shí)現(xiàn),我們可以使用下面的對(duì)象:

  • 設(shè)備 ID 的 SparseArray 跟蹤已連接到設(shè)備的游戲控制器。
  • 一個(gè) Handler 來處理設(shè)備事件。當(dāng)一個(gè) app 啟動(dòng)或者恢復(fù)時(shí),Handler 接收一個(gè)消息來開始輪詢游戲控制器的斷開。Handler 將啟動(dòng)一個(gè)循環(huán)來檢查每個(gè)已知連接的游戲控制器并且查看是否返回一個(gè)設(shè)備 ID。返回 null 表示游戲控制器斷開。當(dāng) app 暫停時(shí),Handler 停止輪詢。
  • 一個(gè) InputManagerCompat.InputDeviceListenerMap 對(duì)象。我們會(huì)使用這個(gè) 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);
    }
}

實(shí)現(xiàn)繼承 HandlerPollingMessageHandler,并重寫 handleMessage() 方法。這個(gè)方法檢查已連接的游戲控制器是否已經(jīng)斷開并且通知已注冊(cè)的 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;
        }
    }
}

至于啟動(dòng)和停止輪詢游戲控制器的斷開,重寫這些方法:

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() 方法檢測(cè)輸入設(shè)備是否已添加。當(dāng)系統(tǒng)通知一個(gè)動(dòng)作事件時(shí),檢查這個(gè)事件是否從已經(jīng)跟蹤過的還是新的設(shè)備 ID 中發(fā)出。如果是新的設(shè)備 ID,通知已注冊(cè)的 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 對(duì)象發(fā)送一個(gè) DeviceEvent Runnable 對(duì)象到消息隊(duì)列來實(shí)現(xiàn)。DeviceEvent 包含了一個(gè) InputManagerCompat.InputDeviceListener 的引用。當(dāng) DeviceEvent 運(yùn)行時(shí),適當(dāng)?shù)?listener 回調(diào)方法會(huì)被調(diào)用,標(biā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)有兩個(gè) InputManagerCompat 的實(shí)現(xiàn):一個(gè)可以在運(yùn)行 Android 4.1 或者更高版本的設(shè)備上工作,另一個(gè)可以在運(yùn)行 Android 2.3 到 Android 4.0 的設(shè)備上工作。

使用特定版本的實(shí)現(xiàn)

特定版本切換的邏輯是在一個(gè)充當(dāng) factory 的類中實(shí)現(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)在我們可以簡(jiǎn)單地實(shí)例化一個(gè) InputManagerCompat 對(duì)象,并且在主 View 中注冊(cè) InputManagerCompat.InputDeviceListener。由于我們建立的版本切換邏輯,我們的游戲會(huì)自動(dòng)為設(shè)備上運(yùn)行的 Android 版本使用適當(dāng)?shù)膶?shí)現(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)該可以一致地處理運(yùn)行著 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 類中找到這個(gè)兼容性的完整的代碼。

上一篇:聯(lián)系人信息下一篇:緩存Bitmap