Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 鍵盤監聽與按鍵模擬的可行性調研

編輯:Android 開發實例

1. 鍵盤監聽分析

Android 的按鍵會產生一個 KeyEvent,而這個事件只會被最上層取得焦點的 Activity 與 View 收到。所有按鍵事件首先觸發 public boolean dispatchKeyEvent(KeyEvent event),SDK 對它的說明如下:

public boolean dispatchKeyEvent(KeyEvent event)
Since: API Level 1

Called to process key events. You can override this to intercept all key
events before they are dispatched to the window. Be sure to call this
implementation for key events that should be handled normally.

Returns: true if this event was consumed.

接著會觸發 public void onUserInteraction():

public void onUserInteraction()
Since: API Level 3

Called whenever a key, touch, or trackball event is dispatched to the
activity. Implement this method if you wish to know that the user has
interacted with the device in some way while your activity is running.
This callback and onUserLeaveHint() are intended to help activities manage
status bar notifications intelligently.

Note that this callback will be invoked for the touch down action that
begins a touch gesture, but may not be invoked for the touch-moved and
touch-up actions that follow.

按下按鍵後接著觸發 public boolean onKeyDown(int keyCode, KeyEvent event),一般處理按壓行為就是覆寫這個方法。

事件觸發順序

觸控(螢幕)時:先 dispatchTouchEvent,再 onUserInteraction,然後 onTouchEvent。若判定為點擊,則接著走一次 ACTION_DOWN 與 ACTION_UP 的完整流程;注意 ACTION_UP 階段不會再觸發 onUserInteraction(可查原始碼確認)。

按鍵時:先 dispatchKeyEvent,再 onUserInteraction,然後 onKeyDown;按下後放開則是兩段,再走一次 dispatchKeyEvent → onUserInteraction → onKeyUp。與觸控不同的是,按鍵放開時 onUserInteraction 也會觸發。

此外,繼承 InputMethodService 並覆寫其 onKeyDown(int keyCode, KeyEvent event),同樣可以監聽按鍵。SDK 說明寫得很明白:

Use this to monitor key events being delivered to the application. We get
first crack at them, and can either resume them or let them continue to
the app.

也就是說,輸入法比應用程式更早拿到按鍵,可以自行攔下或繼續往下傳遞。

小結:Android 的按鍵以 KeyEvent 形式存在,且只有最上層取得焦點的 Activity 與 View 能收到,其他進程無法攔截,因此跨進程的全域鍵盤監聽是做不到的。

2. 鍵盤模擬分析

在 SDK 1.6 之前,可以透過 android.view.IWindowManager 注入按鍵。核心寫法如下:

package org.anddev.android.simualtekeys;

import android.app.Activity;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.ServiceManager;
import android.view.IWindowManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

public class SimualteKeyInput extends Activity {

    /* The WindowManager capable of injecting keyStrokes. */
    final IWindowManager windowManager = IWindowManager.Stub
            .asInterface(ServiceManager.getService("window"));

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        /* Make the button do the menu-popup. */
        this.findViewById(R.id.cmd_simulate_key).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        /* 放到子執行緒,避免阻塞 GUI */
                        new Thread(new Runnable() {
                            public void run() {
                                simulateKeystroke(KeyEvent.KEYCODE_SOFT_LEFT);
                            }
                        }).start();
                    }
                });
    }

    /** Create a dummy-menu. */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean supRetVal = super.onCreateOptionsMenu(menu);
        menu.add(0, 0, "Awesome it works =)");
        return supRetVal;
    }

    /** 一次完整的按鍵 = DOWN + UP */
    private void simulateKeystroke(int KeyCode) {
        doInjectKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyCode));
        doInjectKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyCode));
    }

    /** 真正負責注入的工作 */
    private void doInjectKeyEvent(KeyEvent kEvent) {
        try {
            windowManager.injectKeyEvent(kEvent.isDown(), kEvent.getKeyCode(),
                    kEvent.getRepeatCount(), kEvent.getDownTime(),
                    kEvent.getEventTime(), true);
        } catch (DeadObjectException e) {
            e.printStackTrace();
        }
    }
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button id="@+id/cmd_simulate_key"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Simulate Menu Key Press" />
</LinearLayout>

這個方法在 1.6 以上的 SDK 無法使用,因為 android.os.ServiceManager 與 android.view.IWindowManager 這兩個套件已被隱藏。要在 framework 層呼叫它,就得在 Android 原始碼環境下用 Android.mk 編寫程式,好處是可以使用 SDK 未開放的套件,編出的產物是一個 jar,並能接受執行參數(例如 autotest -touch 123.0 123.0 模擬點擊座標)。由於 Android 無法直接運行 jar,還需要藉 app_process 來載入。

另一條路是透過輸入法實作按鍵模擬:

getCurrentInputConnection().sendKeyEvent(
        new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode));
getCurrentInputConnection().sendKeyEvent(
        new KeyEvent(KeyEvent.ACTION_UP, keyEventCode));

這樣就完成了一次按下與彈起。代價是使用者必須手動到設定中啟用你的輸入法(程式本身無法把自己設為預設輸入法),而且切換輸入法的 API 需要 android.uid.system 這個系統等級的 uid,只有系統簽名才拿得到。實測即使自行呼叫設定流程,最終仍需重新簽名。整體而言,普通應用程式無法做到按鍵模擬。

3. 用 Test Instrument 模擬按鍵

先建一個被測試的專案 TestApp:

Package Name    : com.android.testapp
Activity Name   : MainActivity
Application Name: TestApp

MainActivity:

package com.android.testapp;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public int sum(int a, int b) {
        return a + b;
    }

    public int substract(int a, int b) {
        return a - b;
    }
}

接著新建 Source Folder 名為 test,在其中建立 com.android.testapp.test 套件,並定義 TestMainActivity:

package com.android.testapp.test;

import com.android.testapp.MainActivity;

import android.app.Instrumentation;
import android.content.ContentResolver;
import android.test.ActivityInstrumentationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.util.Log;
import android.view.KeyEvent;

public class TestMainActivity extends ActivityInstrumentationTestCase<MainActivity> {

    private Instrumentation mInst = null;
    private ContentResolver mContentResolver = null;

    public TestMainActivity() {
        super("com.android.testapp", MainActivity.class);
    }

    public TestMainActivity(String pkg, Class<MainActivity> activityClass) {
        super(pkg, activityClass);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mInst = getInstrumentation();
        mContentResolver = mInst.getContext().getContentResolver();
        Log.i("test", "setup");
    }

    public void testStartActivity() throws Exception {
        // 送出按鍵事件
        mInst.sendCharacterSync(KeyEvent.KEYCODE_1);
        Log.i("test", "send key 1");
        mInst.waitForIdleSync();
    }

    @MediumTest
    public void testSum() {
        assertEquals(3, getActivity().sum(1, 2));
        mInst.sendCharacterSync(KeyEvent.KEYCODE_0);
        Log.i("test", "send key 0");
        mInst.waitForIdleSync();
    }

    @MediumTest
    public void testSubstract() {
        assertEquals(-1, getActivity().substract(1, 2));
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.android.testapp"
    android:versionCode="1"
    android:versionName="1.0.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="android.test.runner" />
    </application>

    <instrumentation android:targetPackage="com.android.testapp"
        android:name="android.test.InstrumentationTestRunner"
        android:label="Test Unit Tests" />
</manifest>

執行步驟:先把 TestApp 的 Run Configuration 設為「do nothing」,避免一執行就順手啟動主程式;接著執行專案把 APK 裝到模擬器;用 adb shell pm list packages 確認已安裝;最後執行:

adb shell am instrument -e class com.android.testapp.test.TestMainActivity \
    -w com.android.testapp/android.test.InstrumentationTestRunner

(指令建議手動輸入,複製貼上容易出錯。)測試跑完後看 logcat,可以確認輸入法確實攔到了測試程式送出的按鍵。

翻閱 Instrumentation 的原始碼可見,sendKeySync 這類方法底層呼叫的正是 injectKeyEvent:

public void sendKeySync(KeyEvent event) {
    validateNotAppThread();
    try {
        (IWindowManager.Stub.asInterface(ServiceManager.getService("window")))
                .injectKeyEvent(event, true);
    } catch (RemoteException e) {
    }
}

而 IWindowManager 在 1.6 之後已被隱藏,因此有說法認為只能在原始碼環境下編譯使用。實際上,在 adb 的 monkey 與 input 指令中都能看到它的身影:

IWindowManager.Stub
    .asInterface(ServiceManager.getService("window"))
    .injectKeyEvent(down, true);
IWindowManager.Stub
    .asInterface(ServiceManager.getService("window"))
    .injectKeyEvent(up, true);

於是可以換個思路:讓程式去呼叫命令列。新建一個 runcmd 專案:

package zy.runcmd;

import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class runcmd extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            Runtime.getRuntime().exec("am instrument -e class "
                    + "com.android.testapp.test.TestMainActivity -w "
                    + "com.android.testapp/android.test.InstrumentationTestRunner");
            Log.i("run", "success!!!!!!!!!");
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("run", e.toString());
        }
    }
}

執行後 logcat 會印出 success,並可看到 TestApp 被啟動、送出的按鍵 7 與 8 都被輸入法攔下。

4. injectKeyEvent 的跨進程限制

嘗試跨進程注入按鍵會被拒絕:

WARN/WindowManager(55): Permission denied: injecting key event from pid 460
uid 10037 to window Window{43e0fe80
com.android.contacts/com.android.contacts.DialtactsActivity paused=false}
owned by uid 10001

即使補上 <uses-permission android:name="android.permission.INJECT_EVENTS" /> 也一樣無效。

結論:Test Instrument 底層呼叫的 injectKeyEvent,在測試環境下只能把模擬按鍵送給「被測試的那個 Activity」。跨進程傳遞時一律出現 Permission denied,加上權限宣告也沒用。推測是這個 API 僅允許系統等級進程或同進程內使用。

5. 讓 APK 以目標程式的身分運行

測試目標是 android.uid.phone(撥號程式),希望把按鍵注入其中。做法是在 Manifest 加入:

android:sharedUserId="android.uid.phone"

此時直接安裝會失敗並提示簽名不符,需要用平台密鑰重新簽名。

流程如下:

1. 用 Eclipse 編出 APK(此時無法安裝)。

2. 用壓縮工具打開 APK,刪除 META-INF 下的兩個簽名檔。

3. 找到平台密鑰,在原始碼目錄中的位置是 build/target/product/security 下的 platform.pk8 與 platform.x509.pem。

4. 用 Android 提供的 signapk 工具重新簽名,可以寫成一個批次檔:

@ECHO OFF
Echo Auto-sign Created By Dave Da illest 1
Echo Update.apk is now being signed and will be renamed to updated.apk

java -jar signapk.jar platform.x509.pem platform.pk8 update.apk updated.apk

Echo Signing Complete
Pause
EXIT

把去簽後的 APK 取名 update.apk 放到工具目錄執行,會產生 updated.apk,用壓縮工具打開可確認簽名已替換。裝到機器上實測,確實能在撥號盤上模擬按鍵,模擬器與 G2 都可以。

但這個方案有明顯限制:產出的程式只能在原廠 Android 系統或自行編譯的系統上安裝,因為只有這些環境才拿得到平台密鑰。實測在 HTC G2 上可行,換到 MOTO MILESTONE 就裝不上,應是簽名金鑰不一致所致。

總結

由於 injectKeyEvent 無法跨進程,只能在使用被模擬程式所屬簽名的環境中呼叫。要在別人的程式裡送按鍵,前提是雙方使用相同簽名並共用同一個 sharedUserId;要在系統程式中模擬,則需要取得該系統的簽名金鑰。不同廠商的 Android 系統金鑰不同,拿到對應的 key 就能在該環境下完成按鍵模擬——這也是為什麼這類能力最終都指向「系統簽名」這道門檻。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved