Android监听Home键实例详解
本文实例讲述了Android监听Home键的方法。分享给大家供大家参考,具体如下:
将到android中Home键的监听,很多人第一反应时重写相应Activity的onKeyDown()方法,监听当按下的键的keyCode为KEYCODE_HOME时,进行自己的相应的处理。如:
@Override publicbooleanonKeyDown(intkeyCode,KeyEventevent){ if(keyCode==KeyEvent.KEYCODE_HOME){ stopService(mIntentService); returntrue; } returnsuper.onKeyDown(keyCode,event); }
但是这样的监听是不能监听到HOME键的。这样的方法只能监听到BACK,MENU键。那么怎么监听Home键了?
1.新建一个监听Home键的Listener
publicclassHomeListener{ staticfinalStringTAG="HomeListener"; privateContextmContext; privateIntentFiltermFilter; privateOnHomePressedListenermListener; privateInnerReceviermRecevier; //回调接口 publicinterfaceOnHomePressedListener{ publicvoidonHomePressed(); publicvoidonHomeLongPressed(); } publicHomeListener(Contextcontext){ mContext=context; mFilter=newIntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); } /** *设置监听 * *@paramlistener */ publicvoidsetOnHomePressedListener(OnHomePressedListenerlistener){ mListener=listener; mRecevier=newInnerRecevier(); } /** *开始监听,注册广播 */ publicvoidstartWatch(){ if(mRecevier!=null){ mContext.registerReceiver(mRecevier,mFilter); } } /** *停止监听,注销广播 */ publicvoidstopWatch(){ if(mRecevier!=null){ mContext.unregisterReceiver(mRecevier); } } classInnerRecevierextendsBroadcastReceiver{ finalStringSYSTEM_DIALOG_REASON_KEY="reason"; finalStringSYSTEM_DIALOG_REASON_GLOBAL_ACTIONS="globalactions"; finalStringSYSTEM_DIALOG_REASON_RECENT_APPS="recentapps"; finalStringSYSTEM_DIALOG_REASON_HOME_KEY="homekey"; @Override publicvoidonReceive(Contextcontext,Intentintent){ Stringaction=intent.getAction(); if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){ Stringreason=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(); }elseif(reason .equals(SYSTEM_DIALOG_REASON_RECENT_APPS)){ //长按home键 mListener.onHomeLongPressed(); } } } } } } }
2.在使用的类的onCreate方法中注册Home键的监听
/** *注册Home键的监听 */ privatevoidregisterHomeListener(){ mHomeWatcher=newHomeListener(this); mHomeWatcher.setOnHomePressedListener(newOnHomePressedListener(){ @Override publicvoidonHomePressed(){ //TODO进行点击Home键的处理 Log.i("xsl","0000000000000"); stopService(mIntentService); } @Override publicvoidonHomeLongPressed(){ //TODO进行长按Home键的处理 Log.i("xsl","0000000000000"); } }); mHomeWatcher.startWatch(); }
3.在使用的类的onPause方法中停止监听
mHomeWatcher.stopWatch();
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android资源操作技巧汇总》、《Android视图View技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。