Application Suspend and Resume

Hi All,

I think this may have been covered elsewhere, but I recently had to change the operation of Go Yeti! to support application suspend and resume properly. The issue is that the app kept crashing due to some bug in analytics.init() [check out daily builds forum for more details http://developer.coronalabs.com/forum/2012/10/11/analyticsinit-crash-ios6
].
But then I stumbled into that other bug which locks out the audio when the app is resumed!
http://developer.coronalabs.com/forum/2012/08/12/music-stops-when-phone-goes-sleep
So to give a good user experience, I wanted the game to fully pause during suspend (which could happen due to a phone call or when the user pressed the home button) so that when the user launched the app again (or the call finished), the game was in a useful pause state.

So, first of all, if you just want to get around the audio bug, I recommend the following code:

function onSystemEvent( event )  
 if (event.type == "applicationSuspend") then  
 audio.pause()  
 elseif (event.type == "applicationResume") then  
 audio.resume()  
 end  
end  
Runtime:addEventListener( "system", onSystemEvent ) -- used to catch system events like pause  
  

Thanks to @TimeSpaceMagic for this.

But then, to get the pause and resume stuff working, I started to get paranoid that maybe the phone would go to sleep before the whole game had paused (in my case there are a lot of lines of code just to pause the game as I use transitions everywhere (lesson #1: do not use transitions if you want to easily pause a game!)

So in the end, my code looks something like this:

 if (event.type == "applicationSuspend") then  
 audio.pause()  
  
 elseif (event.type == "applicationResume") then  
audio.resume()  
pause\_game() -- my own function to pause the game  
display\_pause\_message() -- message to tell user that the game is paused  
end  
  
Runtime:addEventListener( "system", onSystemEvent ) -- used to catch system events like pause  
  

The reason for putting the pause_game() in the applicationResume section is that otherwise, the game could quit mid-pause function, the go to applicationResume in this state, which could cause issues! Also (very importantly) there is a chance that the audio.pause() will not execute correctly before the app suspends if there is more code in that branch … I guess that depends on the inner workings of Corona/IOS

May be something useful for someone here to save time
Anthony

www.nevistech.com
[import]uid: 87194 topic_id: 31999 reply_id: 331999[/import]