編輯:關於 Android 程式設計
Home 鍵監聽是 Android 開發裡的經典難題。本文把不同時期的解法整理成一條時間線,說明為什麼某些寫法在 2.2 堪用、到 4.0 就完全失效。
讀 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。
早期系統的做法是先拿權限,讓鍵盤守衛失效:
<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.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 控件用法總結》。
Android 狀態列通知完整指南:Notification 與 NotificationManager 用法詳解
在 Android 裡推送一條狀態列通知其實並不複雜,但真要把它用得好,牽涉到的細節卻不少。本文把通知的發送、更新、清除,以及鈴聲、振動、呼吸燈、自訂版面等常見設定一次梳
Android 開發常見錯誤訊息大整理與排解思路
做 Android 開發,除錯佔掉大半時間。本文把日常最常遇到的錯誤訊息整理成一份速查表,並附上原因與解法。與其死記硬背,不如理解背後機制——多數錯誤其實都指向幾個固定的
RecyclerView 多種 Item 布局加載實作
RecyclerView 要實現多種 Item 布局,關鍵在於 Adapter 的 getItemViewType() 與 onCreateViewHolder()。開發
用 emulator -data 參數從 CMD 啟動 Android 模擬器
在命令列(CMD)中使用 emulator.exe 啟動 Android 模擬器有兩種方式: ・emulator -avd(AVD 名稱) ・emulator -data