Recognize application losing focus

Is there a way in Codea to detect when the user has switches apps and is coming back to your app. Even though I am now looking for the trigger when the user comes back to the application, getting a trigger when the user is about to leave the app would be nice as well.

Sadly, No

@jeroenb42 I don’t have anything when the app loses focus, but this code can be use to tell when the app comes back into focus. Just run the code, switch apps then come back to this one again. It can probably be condensed some, but I have to leave and don’t have time.

EDIT:code changed to reduce calculations and to get lost focus time.

function setup()   

function draw()
    if checkFocus() then
        print("focus regained after "..cFSdiff.." seconds")

function checkFocus()
    local FS=d.hour*3600+d.min*60+d.sec
    if cFS==nil then
    if cFSdiff>1 then
        return true
    return false

Woops @dave1708 beat me to it.

Actually…it would kind of be nice to know when this happens. Seems like Codea should be able to forward the iOS background/resume events without much pain. @Simeon what do you think?

I’ve always wanted a function close() like the opposite of setup, would make game saving a data saving/deleting much easier rather than having to hack around it or run the process every few steps which can take up lots of memory depending on how many calls are made…

@jeroenb42 I changed the above code to reduce the number of calculations and to save the number of seconds that the app wasn’t in focus.

@Luatee, Wait, how would it take up a lot of memory? Does Codea Not erase old saves?

@Prynok, if I have a game which I want to save the state of at that current point or when the player leaves the game, it causes a fps drop due to various tables being converted to strings and ammo/physics bodies/player type/guns/equipped guns… The point is that the list goes on and on when more ideas come in to the game so instead of having to save at random parts during the play process, just run it once at the end which is the exact state you want it in when you resume.