Android监听Home键实例详解
程序员文章站
2024-02-20 14:59:52
本文实例讲述了android监听home键的方法。分享给大家供大家参考,具体如下:
将到android中home键的监听,很多人第一反应时重写相应activity的onk...
本文实例讲述了android监听home键的方法。分享给大家供大家参考,具体如下:
将到android中home键的监听,很多人第一反应时重写相应activity的onkeydown()方法,监听当按下的键的keycode为keycode_home时,进行自己的相应的处理。如:
@override public 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程序设计有所帮助。