編輯:關於 Android 程式設計
智慧電視與電視盒子愈來愈普及,早期主打影片播放,如今則在補強影音的同時加入遊戲能力,剛好也趕上「電視遊戲機解禁」的時機點。
現今大部分的 Android 手遊都能在電視終端上跑起來,其中少數原生支援手把(例如 MOGA 手把)的作品可以直接當作電視遊戲使用。但其他類型的手遊(射擊、賽車、動作等)若要在電視上玩,就得改寫操控模式,把觸控螢幕的操作邏輯轉換為手把實體鍵的操作。
本文說明如何使用 /system/bin/ 下的 Input 指令來模擬按鍵與觸控螢幕操作。呼叫 Input 指令需要 root 權限。
程式執行結果如下:

這裡刻意不把程式碼濃縮成全局靜態方法,而是讓 process 與 os 這兩個變數的生命週期延續到 App 結束。這樣做可以省下每次執行指令都要重新初始化與釋放的時間——畢竟模擬操控往往需要連續下達大量指令。
package com.hellogv.slinput;
import java.io.DataOutputStream;
import java.io.IOException;
import android.util.Log;
/**
* 呼叫 su 執行 input 指令
* 全局只呼叫一次 init() 與 exit(),其間可多次呼叫 run()。
*/
public class RootCommand {
private 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());
} catch (IOException e) {
Log.e(TAG, getExceptionMessage(e));
}
}
/**
* 模仿 shell 執行指令,必須先 root 才能使用
*
* @param command
* @return
*/
public boolean run(String command) {
try {
os.writeBytes(command + "\n");
os.flush();
} catch (Exception e) {
Log.e(TAG, getExceptionMessage(e));
return false;
}
return true;
}
/**
* 結束 shell
*/
public void release() {
try {
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.e(TAG, getExceptionMessage(e));
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
}
private static String getExceptionMessage(Exception ex) {
String result = "";
StackTraceElement[] stes = ex.getStackTrace();
for (int i = 0; i < stes.length; i++) {
result = result + stes[i].getClassName() + "." + stes[i].getMethodName()
+ " " + stes[i].getLineNumber() + "line" + "\r\n";
}
return result;
}
}
Input 指令的格式直接寫在註解裡,分別是 input keyevent、input swipe 與 input tap:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootCommand.init();
// 模擬按下 Home 鍵
btnTestKey = (Button) this.findViewById(R.id.btnTestKey);
btnTestKey.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 指令格式:input keyevent keycode
rootCommand.run("/system/bin/input keyevent " + KeyEvent.KEYCODE_HOME);
}
});
// 模擬滑動觸控螢幕
btnTestSwipe = (Button) this.findViewById(R.id.btnTestSwipe);
btnTestSwipe.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int x2 = MainActivity.this.getWindow().getDecorView().getWidth() - 10;
// 先回到桌面
rootCommand.run("/system/bin/input keyevent " + KeyEvent.KEYCODE_HOME);
// 滑動桌面,指令格式:input swipe x1 y1 x2 y2
for (int i = 0; i < 4; i++) {
rootCommand.run("/system/bin/input swipe 10 300 " + x2 + " 400");
rootCommand.run("/system/bin/input swipe " + x2 + " 300 10 400");
}
}
});
// 模擬點擊觸控螢幕
btnTestTap = (Button) this.findViewById(R.id.btnTestTap);
btnTestTap.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int[] location = new int[2];
btnTestSwipe.getLocationOnScreen(location);
int x = location[0] + btnTestSwipe.getWidth() / 2;
int y = location[1] + btnTestSwipe.getHeight() / 2;
// 模擬點擊 btnTestSwipe 的位置
rootCommand.run("/system/bin/input tap " + x + " " + y);
}
});
// 離開程式
btnExit = (Button) this.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
rootCommand.release();
MainActivity.this.finish();
}
});
// 判斷是否已 root,未 root 則無法使用
if (RootTools.isRootAvailable() == false) {
Toast.makeText(this, "本程式需要使用 ROOT 權限。", Toast.LENGTH_SHORT).show();
this.finish();
}
}
實際改造一款手遊時,思路是這樣:先攔截手把的按鍵事件(在 Activity 中覆寫 onKeyDown()/onKeyUp(),或用 dispatchKeyEvent() 攔全場),再把每個按鍵對應到手遊原本需要的觸控手勢上。例如把十字鍵的上下映射成 input swipe 的垂直滑動,把 A 鍵映射成 input tap 點擊畫面中央。因為每一次 input 都是一條 shell 指令,啟動成本不低,若遊戲需要連續快速的操作,會明顯感到延遲——這是這個方案最大的侷限。
另外,這類做法只適合自有裝置或專用機,Google Play 對使用 root 的應用有明確規範。若只是想把觸控操作轉為手把輸入,也可以研究 Android 本身的 InjectInputEvent 或 uinput 子系統,不必依賴 root 開 shell。
有興趣的人可以動手實測這份範例,相信對你的 Android 開發會有幫助。
Android 好奇寶寶(05):PopupWindow 與懸浮窗
之所以把 PopupWindow 與懸浮窗放在一起講,是因為兩者的實現原理基本一致,只是細節上略有差異。 原理 使用系統服務 WindowManagerService,把
Android 如何取得初始狀態下 View 的寬高
在自訂 View 或下拉刷新等情境中,常常需要在初始化階段取得 View 的寬高。然而,在 View 尚未完成 measure 與 layout 之前,getHeight
Android 4.2.2 Stagefright 中 OMX 編解碼器組件的控制流追蹤
把控制流單獨拎出來講,是因為它具備很強的層次性,結構上高度統一,而且 API 函數的設計必須實現 OMX 架構約定的那套接口。理解了這一層,後面的數據流分析才有依據。一、
emulator-arm.exe應用程式錯誤?AVD與SD卡設定排查
若Eclipse啟動AVD時出現emulator-arm.exe錯誤,可檢查AVD名稱與SD卡設定。名稱建議以小寫英數為主,避免特殊字元。 若已建立sdcard.img,