衆所周知,咱們監聽返回鍵事件,沒法是下面兩個方法: java
public void onBackPressed() { //do something //super.onBackPressed(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ //do something } return super.onKeyDown(keyCode, event); }
因而乎,咱們理所固然的想到,監聽Home鍵的方法是:if(keyCode == KeyEvent.KEYCODE_HOME)。但實際上,這樣是行不通的,由於此時home鍵的消息在framework層就已經被攔截,因此,咱們在應用中經過此方法是沒法監聽到Home鍵的消息的。那麼咱們如何捕獲Home鍵事件,並做出相應處理呢?其實系統仍是給咱們發出廣播的,下面,就跟你們分享一下,封裝好了的監聽Home鍵的方法: app
/** * Home鍵監聽封裝 * * @author way * */ public class HomeWatcher { static final String TAG = "HomeWatcher"; private Context mContext; private IntentFilter mFilter; private OnHomePressedListener mListener; private InnerRecevier mRecevier; // 回調接口 public interface OnHomePressedListener { public void onHomePressed(); public void onHomeLongPressed(); } public HomeWatcher(Context context) { mContext = context; mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); } /** * 設置監聽 * * @param listener */ public void setOnHomePressedListener(OnHomePressedListener listener) { mListener = listener; mRecevier = new InnerRecevier(); } /** * 開始監聽,註冊廣播 */ public void startWatch() { if (mRecevier != null) { mContext.registerReceiver(mRecevier, mFilter); } } /** * 中止監聽,註銷廣播 */ public void stopWatch() { if (mRecevier != null) { mContext.unregisterReceiver(mRecevier); } } /** * 廣播接收者 */ class InnerRecevier extends BroadcastReceiver { final String SYSTEM_DIALOG_REASON_KEY = "reason"; final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions"; final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"; final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; @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_DIALOG_REASON_KEY); if (reason != null) { Log.e(TAG, "action:" + action + ",reason:" + reason); if (mListener != null) { if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) { // 短按home鍵 mListener.onHomePressed(); } else if (reason .equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) { // 長按home鍵 mListener.onHomeLongPressed(); } } } } } } }
接下來,咱們須要在應用中開啓監聽,下面是以在Activity中的應用爲例: ide
/** * 應用HomeWatcher小例 * * @author way * */ public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private HomeWatcher mHomeWatcher; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHomeWatcher = new HomeWatcher(this); mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() { @Override public void onHomePressed() { Log.e(TAG, "onHomePressed"); } @Override public void onHomeLongPressed() { Log.e(TAG, "onHomeLongPressed"); } }); mHomeWatcher.startWatch(); } @Override protected void onPause() { super.onPause(); mHomeWatcher.stopWatch();// 在onPause中中止監聽,否則會報錯的。 } }