ACTIVATE/DEACTIVATE events don't work for a mobile game app using starling framework

124 Views Asked by At

So I'm developping a mobile game using the framework starling, and I want the game to pause when I hit the home/back button on my phone, and of course to resume when going back to the game. I did some research and I tried the following:

this.addEventListener(FlashEvent.DEACTIVATE, stopGame);
this.addEventListener(FlashEvent.ACTIVATE, continueGame);

private function continueGame(event:FlashEvent):void 
{
    ...
}
private function stopGame(event:FlashEvent):void 
{
    ...
}

I had to add a new class called FlashEvent that extends flash.events.Event, because I use starling Event and flash Event in the same class, and when I use flash.events.Event I get this error:

Error: Access of undefined property flash

And the same thing for starling.events.Event.

So I used the code above and tried it out in my phone, but when I hit back/home, the game keeps going and the music keeps playing.

My question is: what is the correct way to dispatch the activate/deactivate event in an air mobile app?

2

There are 2 best solutions below

3
crooksy88 On BEST ANSWER

Used in your main startup class. (note that in this example 'app:Main' is the class I call the Starling start method.

Note that you should determine event classes with: starling.events.Event.XXX flash.events.Event.XXX

_mStarling.addEventListener(starling.events.Event.ROOT_CREATED, 
function onRootCreated(event:Object, app:Main):void
{

_mStarling.removeEventListener(starling.events.Event.ROOT_CREATED, onRootCreated);

app.start(assets);

_mStarling.start();

NativeApplication.nativeApplication.addEventListener(
flash.events.Event.ACTIVATE, function (e:*):void { 

_mStarling.start(); 

try {
//  optionally call some other methods
} catch(e:Error) {

}
});

NativeApplication.nativeApplication.addEventListener(
flash.events.Event.DEACTIVATE, function (e:*):void { 

try{
//  optionally call some other methods before stopping
} catch(e:Error) {

}
_mStarling.stop(); 
}); 

});
0
MarkReedZ On

My code

public function Main()
{
  stage.addEventListener(flash.events.Event.DEACTIVATE, onDeactivate);
  stage.addEventListener(flash.events.Event.ACTIVATE, onActivate);
}

And you set a paused boolean and check for it at the top of your game loop:

if ( paused ) return;

If you have animations you use a juggler and if you aren't calling advanceTime on the juggler it is paused.