監聽android home鍵的實作方式 1. 通過廣播的方式監聽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)) {
//表示按了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.view.Menu;
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)) {
//表示按了home鍵,程式到了背景
Toast.makeText(getApplicationContext(), "home", 1).show();
}else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){
//表示長按home鍵,顯示最近使用的程式清單
}
}
}
};
}