对于Home键的监听不是那么容易,因为Home键可以将程序退出放在后台,所以这个事件是直接分发给系统,系统接收到之后做相应处理,Home键的事件不是直接传递到应用里面.所以在上述监听Back键的代码中,相应的回调中是收不到Home键的事件的.
参考文后的博客链接,对Home键的监听主要通过注册广播接收器实现,拦截让窗口关闭的系统动作,然后根据Intent里面的具体参数,分析当前到底是Home键, 应用切换键,还是其他功能按键.
private BroadcastReceiver homePressReceiver =new BroadcastReceiver(){
String SYSTEM_REASON ="reason";
String SYSTEM_HOME_KEY ="homekey";
String SYSTEM_HOME_KEY_LONG ="recentapps";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_REASON);
if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
ProApplication.getInstance().finishAllActivity();
System.exit(0);
}else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){
ProApplication.getInstance().finishAllActivity();
System.exit(0);
}}}};
这样可以在主界面保证home键之后杀死整个程序,但是如果你是在二级三级界面按下home键,这样处理还是会有问题,开启的activity会存在在栈中无法销毁
可以在application中,把每次打开的activity添加到集合里,返回的时候再去移除,按下home键的时候拿出集合里面的activity挨个销毁,这样就不会有问题了
public void addActivityToMap(String tag, Activity activity){
if(mActivityMap ==null){
mActivityMap =new HashMap<>();
}
mActivityMap.put(tag, activity);
}
public void removeActivityFromMap(String tag){
if(mActivityMap !=null){
if(mActivityMap.containsKey(tag)){
mActivityMap.remove(tag);
}
}
}
public void finishAllActivity() {
if (mActivityMap ==null) {
return;
}
CollectionactivityVaule =mActivityMap.values();
if (activityVaule !=null) {
Iteratoriter =activityVaule.iterator();
if (iter ==null) {
return;
}
while ((iter.hasNext())) {
Activity activity =iter.next();
if (activity !=null) {
activity.finish();
}
}
}
}