萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 手遊移植電視遊戲:Input 指令模擬按鍵與觸控實戰

大多數 Android 手遊可在 Android TV/機頂盒運行,但缺乏手柄支援。本文實戰演示如何利用 /system/bin/input 指令 (需 Root 權限) 模擬按鍵事件、觸控點擊、滑動手勢,將觸控操作映射為手柄實體按鍵,實現手遊無縫轉電視遊戲體驗。附完整 Java 封裝類 RootCommand 與 Activity 整合範例。

核心原理

  • input 是 Android 系統內建工具,位於 /system/bin/input,支援 keyevent、tap、swipe、text 等子命令。
  • 需 Root 權限 (UID 0) 執行,透過 Runtime.getRuntime().exec("su") 獲取 Shell,寫入指令流。
  • 長期保持 Process 與 DataOutputStream 存活,避免重複 su 啟動開銷 (每次約 200-500ms)。

input 指令速查表

子命令語法範例說明
keyeventinput keyevent <KEYCODE>input keyevent 3 (HOME)、82 (MENU)、19/20/21/22/23 (方向鍵/確定)發送鍵盤按鍵事件,KEYCODE 參考 KeyEvent 類常量
tapinput tap <x> <y>input tap 540 960模擬單點觸控點擊 (螢幕座標)
swipeinput swipe <x1> <y1> <x2> <y2> [duration_ms]input swipe 100 500 900 500 300模擬滑動手勢,可選持續時間
textinput text <string>input text "hello%sworld"模擬鍵盤輸入文字,空格用 %s
rollinput roll <dx> <dy>input roll 10 0模擬滾輪/軌跡球 (罕用)

RootCommand 封裝類 (核心代碼)

package com.hellogv.slinput;

import android.util.Log;
import java.io.DataOutputStream;
import java.io.IOException;

public class RootCommand {
    private static final String TAG = "RootCommand";
    private Process process = null;
    private DataOutputStream os = null;

    public void init() {
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            Log.d(TAG, "Root shell acquired");
        } catch (IOException e) {
            Log.e(TAG, "init failed", e);
        }
    }

    /** 發送指令,自動換行 flush */
    public boolean run(String command) {
        if (os == null) return false;
        try {
            os.writeBytes(command + "\n");
            os.flush();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "run failed: " + command, e);
            return false;
        }
    }

    /** 釋放資源 */
    public void release() {
        try {
            if (os != null) {
                os.writeBytes("exit\n");
                os.flush();
            }
            if (process != null) process.waitFor();
        } catch (Exception e) {
            Log.e(TAG, "release error", e);
        } finally {
            try {
                if (os != null) os.close();
            } catch (IOException ignored) {}
            if (process != null) process.destroy();
            process = null; os = null;
        }
    }
}

Activity 整合範例:模擬 HOME、滑動桌面、點擊按鈕

public class MainActivity extends AppCompatActivity {
    private RootCommand rootCommand = new RootCommand();
    private Button btnHome, btnSwipe, btnTap, btnExit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Root 檢查
        if (!RootTools.isRootAvailable()) { // 需引入 RootTools 庫
            Toast.makeText(this, "需 ROOT 權限", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        rootCommand.init();

        btnHome = findViewById(R.id.btnHome);
        btnSwipe = findViewById(R.id.btnSwipe);
        btnTap = findViewById(R.id.btnTap);
        btnExit = findViewById(R.id.btnExit);

        // 模擬 HOME 鍵
        btnHome.setOnClickListener(v -> 
            rootCommand.run("/system/bin/input keyevent " + KeyEvent.KEYCODE_HOME));

        // 模擬左右滑動桌面
        btnSwipe.setOnClickListener(v -> {
            int width = getWindow().getDecorView().getWidth() - 10;
            rootCommand.run("/system/bin/input keyevent " + KeyEvent.KEYCODE_HOME); // 先回桌面
            for (int i = 0; i < 4; i++) {
                rootCommand.run("/system/bin/input swipe 10 300 " + width + " 400");
                rootCommand.run("/system/bin/input swipe " + width + " 300 10 400");
            }
        });

        // 模擬點擊 btnSwipe 按鈕中心
        btnTap.setOnClickListener(v -> {
            int[] loc = new int[2];
            btnSwipe.getLocationOnScreen(loc);
            int x = loc[0] + btnSwipe.getWidth() / 2;
            int y = loc[1] + btnSwipe.getHeight() / 2;
            rootCommand.run("/system/bin/input tap " + x + " " + y);
        });

        btnExit.setOnClickListener(v -> {
            rootCommand.release();
            finish();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rootCommand.release();
    }
}

手柄映射架構設計建議

  1. 輸入層:InputDevice + KeyEvent / MotionEvent (手柄/鍵盤/鼠標) → 統一事件總線。
  2. 映射層:配置檔 (JSON/ProtoBuf) 定義 GamepadButton → InputCommand 映射 (如 DPAD_UP → "input swipe 540 1500 540 500 200" / A → "input tap 540 1800")。
  3. 執行層:RootCommand 發送指令;或無 Root 方案:Instrumentation.sendKeyEvent (需簽名權限) / AccessibilityService 模擬手勢 (Android 7.0+)。
  4. 配置 UI:提供遊戲內映射編輯器,支援多款手柄預設、自訂導出分享。

注意事項與風險

  • Root 風險:安全性降低、SafetyNet/Play Integrity 失效、保固失效、OTA 更新失敗。生產環境慎用。
  • 座標相容性:不同解析度/縱橫比裝置座標不同,需按比例換算或使用相對座標 (百分比)。
  • 輸入延遲:Shell 啟動、指令解析、InputReader/InputDispatcher 處理,總延遲 20-50ms,競速類遊戲可能明顯。
  • 安全政策:Android 10+ 限制非系統應用使用 input 指令,甚至移除 /system/bin/input。需簽名權限或系統應用身份。
  • 替代方案:遊戲原生支援手柄 (HID 標準) → 最佳;修改遊戲 APK 注入手柄邏輯 (Xposed/LSPosed 模組) → 免 Root 但需框架;雲遊戲串流 (Moonlight/Steam Link) → 完全規避本地模擬。

總結

利用 input 指令模擬觸控/按鍵,是實現手遊轉電視遊戲的快速原型驗證路徑。核心在於 RootCommand 長連接 Shell 減少開銷、座標相對化適配多裝置、映射配置外部化支援多遊戲。但受限於 Root 門檻、安全政策、延遲與相容性,商業級產品應優先推動遊戲原生適配或採用雲串流方案。

copyright © 萬盛學電腦網 all rights reserved