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