游戏需要统计用户退出游戏是按的返回键还是home,因为返回键是自己cocos2dx做的监听,所以这里说一下android Activity里监听Home键方法,亲测可用,这里做个备份其中也是参考别人的代码实现的,路径没有记住,如有雷同,望见谅……
这里使用的是广播的形式监听Home操作的方法:
首先在MainActivity里添加如下广播,生成一个成员变量:
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)){
Log.i("TT", "##################home键监听");
}
}
}
};
然后在onCreate方法中添加如下方法:
IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(homeReceiver, homeFilter);
注意在应用退出时,在Activity的onDestroy方法中记得注销广播:
@Override
protected void onDestroy() {
super.onDestroy();
if (homeReceiver != null){
try{
unregisterReceiver(homeReceiver);
}catch(Exception e){
Log.e("TT", "unregisterReceiver homeReceiver failure :"+e.getCause());
}
}
}