本文实例讲述了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程序设计有所帮助。
新闻热点
疑难解答
图片精选