本文執行個體講述了Android監聽Home鍵的方法。分享給大家供大家參考,具體如下:
將到android中Home鍵的監聽,很多人第一反應時重寫相應Activity的onKeyDown()方法,監聽當按下的鍵的keyCode為KEYCODE_HOME時,進行自己的相應的處理。如:
@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_HOME) { stopService(mIntentService); return true; } return super.onKeyDown(keyCode, event);}
但是這樣的監聽是不能監聽到HOME鍵的。這樣的方法只能監聽到BACK,MENU鍵。那麼怎麼監聽Home鍵了?
1.建立一個監聽Home鍵的Listener
public class HomeListener { static final String TAG = "HomeListener"; private Context mContext; private IntentFilter mFilter; private OnHomePressedListener mListener; private InnerRecevier mRecevier; // 回調介面 public interface OnHomePressedListener { public void onHomePressed(); public void onHomeLongPressed(); } public HomeListener(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(); } } } } } }}
2.在使用的類的onCreate方法中註冊Home鍵的監聽
/*** 註冊Home鍵的監聽*/private void registerHomeListener() { mHomeWatcher = new HomeListener(this); mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() { @Override public void onHomePressed() { //TODO 進行點擊Home鍵的處理 Log.i("xsl", "0000000000000"); stopService(mIntentService); } @Override public void onHomeLongPressed() { //TODO 進行長按Home鍵的處理 Log.i("xsl", "0000000000000"); } }); mHomeWatcher.startWatch();}
3.在使用的類的onPause方法中停止監聽
mHomeWatcher.stopWatch();
更多關於Android相關內容感興趣的讀者可查看本站專題:《Android開發入門與進階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結》及《Android控制項用法總結》
希望本文所述對大家Android程式設計有所協助。