Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Home 鍵監聽進階:從 Launcher 模式到 Log 側聽的演進

編輯:關於 Android 程式設計

Home 鍵監聽是 Android 開發裡的經典難題。本文把不同時期的解法整理成一條時間線,說明為什麼某些寫法在 2.2 堪用、到 4.0 就完全失效。

思路一:把自己變成 Launcher

讀 Launcher 原始碼時會發現一個巧妙的做法。若 Activity 宣告成下面這樣:

<activity android:name="com.woyou.activity.HomeActivity"
    android:launchMode="singleInstance" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.HOME" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

系統按下 Home 時,會向所有符合條件的 Activity 發送 Intent。接著只要覆寫 onNewIntent,就能在自家頁面收到這個回調。這個做法已驗證可用,但顯而易見會跟真正的桌面互相搶焦點,不適合一般應用。

思路二:廣播側聽(目前最實用)

現在最推薦的方式是攔 ACTION_CLOSE_SYSTEM_DIALOGS,再從 reason 判斷。

private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
    String SYSTEM_REASON = "reason";
    String SYSTEM_HOME_KEY = "homekey";
    String SYSTEM_HOME_KEY_LONG = "recentapps";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_REASON);
            if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                // 按了 home 鍵,程式退到後台
                Toast.makeText(getApplicationContext(), "home", 1).show();
            } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                // 長按 home 鍵,顯示最近使用的程式列表
            }
        }
    }
};

註冊與解除都在自己手上,Activity 或 Service 都能用:

registerReceiver(mHomeKeyEventReceiver,
        new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

完整範例:

package com.example.homedemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 注冊廣播
        registerReceiver(mHomeKeyEventReceiver,
                new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }

    /**
     * 監聽是否點擊了 home 鍵將客戶端推到後台
     */
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";
        String SYSTEM_HOME_KEY_LONG = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    Toast.makeText(getApplicationContext(), "home", 1).show();
                } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                    // 長按 home 鍵,顯示最近程式列表
                }
            }
        }
    };
}

别忘了在 onDestroy 呼叫 unregisterReceiver。

舊方案備查:2.2 及更早版本

早期系統的做法是先拿權限,讓鍵盤守衛失效:

<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>

接著覆寫兩個方法:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (KeyEvent.KEYCODE_HOME == keyCode) {
        // 寫要執行的動作
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public void onAttachedToWindow() {
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    super.onAttachedToWindow();
}

這套寫法只對 2.2 及以前有效。另一條路是改系統原始碼,成本高又不現實,不建議嘗試。

4.0.x 的崩潰點與繞道

把上面的程式碼搬到 4.0.1,this.getWindow().setType(...) 這行會直接丟出例外:

java.lang.IllegalArgumentException: Window type can not be changed after the window is added.

有兩種應對方式。

方式一:改 PhoneWindowManager.java

if (keyCode == KeyEvent.KEYCODE_HOME) {
    // 在這裡發送一個廣播出去
}

應用收到廣播後自行處理。只有做手機 ROM 的人才會走這條路。

方式二:側聽 logcat

private boolean isTesting = true;

class CatchLogThread extends Thread {
    @Override
    public void run() {
        Process mLogcatProc = null;
        BufferedReader reader = null;
        String line;
        while (isTesting) {
            try {
                // 獲取 logcat 日志信息
                mLogcatProc = Runtime.getRuntime().exec(
                        new String[] { "logcat", "ActivityManager:I *:S" });
                reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    if (line.indexOf("android.intent.category.HOME") > 0) {
                        isTesting = false;
                        handler.sendMessage(handler.obtainMessage());
                        Runtime.getRuntime().exec("logcat -c"); // 刪除日志
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
};

Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        Log.i(TAG, "Home key press");
        // do something here
    }
};

這個思路源自《Android 4.0.x Home 鍵事件攔截/監聽》,配合《Android 開發之在程式程序中隨時獲取 logcat 日志信息的方法》一起看會更清楚。要注意它需要 READ_LOGS 權限,而這個權限在正式環境下一般應用拿不到,因此只適用在自有 ROM 或測試環境。

延伸閱讀:《Android 開發入門與進階教程》《Android 資源操作技巧匯總》《Android 視圖 View 技巧總結》《Android 控件用法總結》。

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