Android监听home键

1、在需要监听home键的activity添加广播,生成一个成员变量:

private final BroadcastReceiver homeReceiver = new BroadcastReceiver() {

 final String SYS_KEY = "reason";

 final String SYS_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(SYS_KEY);

 if (reason != null && reason.equals(SYS_HOME_KEY)){

 //写自己需要执行的方法

 }

 }

 } 

};

2、在该activity的onCreate方法中添加:

IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(homeReceiver, homeFilter);

3、在activity的onDestroy方法注销广播:

@Override protected void onDestroy() { 

 super.onDestroy();

 if (homeReceiver != null){

 try{ 

 unregisterReceiver(homeReceiver);

 }

catch(Exception e){ 

 Log.e("log", "unregisterReceiver homeReceiver failure :"+e.getCause());

 }

 } 

 }

这是今天做home键监听时用到的方法。

在网上找了很久,才搜到这个合适的,感谢大神的分享。

原文链接:http://outofmemory.cn/code-snippet/81153/Android-jianting-Home-jian

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容