Check if game entered in foreground/background Scene for Android & iOS

Is there any function in cocos2d-JS to check if game has gone in background/ foreground for android & iOS ?

If yes then what function should I override ?

Thanks in Advance

Here is something I posted a while ago for someone else:

AppDelegate.cpp has the functions void AppDelegate::applicationDidEnterBackground() and void AppDelegate::applicationWillEnterForeground() for when the app goes into the background and comes into the foreground, respectively. They seem to send out custom events “game_on_hide” and “game_on_show”.

I am unfamiliar with custom events but I managed to get something that seems to work.

When the app hides:
var lstnr = cc.EventListenerCustom.create(“game_on_hide”, this.gameHidingFunc);
cc.eventManager.addListener(lstnr, this);

When the app shows:
var lstnr = cc.EventListenerCustom.create(“game_on_show”, this.gameShowingFunc);
cc.eventManager.addListener(lstnr, this);

So, when the app is hidden or shown, the functions - which I have called gameHidingFunc and gameShowingFunc - will be called. Works for me, anyway.

So basically add those event listeners to the scene/layer/node that will handle the game going to the background/foreground, and change this.gameHidingFunc and this.gameShowingFunc to whatever function you want called. (Remember to put this. in front of the function name if necessary.)

2 Likes

Thanks bro ! will try and implement these listener and get back to you … if any issues

Thanks grimfate, this seems very helpful. So if I’ve understood correctly, the “game_on_hide” and “game_on_show” events are created by Cocos right? I don’t need to create them, just create a listener on my scenes to listen to them, is that right?

Thanks.

That is correct. The custom message is already created by cocos; you just have to create a listener to listen for it.

I guess it will be the same in C++, I will give it a go. Thanks

The C++ version? I had a look today and it looked like it doesn’t do it. Might have to send your own custom messages. The functions for showing and hiding, as mentioned in my original comment, is in AppDelegate.cpp if you want to add it yourself.

OK, thanks. I will create them myself in that case.