Tom Krcha's FlashRealtime

Hey amigo!
I am Tom Krcha, Gaming Evangelist at Adobe. These are my notes


Tip: Close Your Android AIR App on Back Button

October 13th, 2010

While developing AIR for Android apps, you should consider whether you need your apps to run in the background, especially if they are highly intensive graphic games.

To make your users even happier, it’s a good idea to close your app when the Back or Home button is pressed to free CPU and memory. Multitasking is a great thing, but if your app doesn’t need to be open, it’s better to close it and maybe save the state of your application. You can read this article on saving state in AIR applications for iOS devices (same should work for Android).

My fellow evangelist Mark Doherty sent me this code, which does the job. It can be helpful to you, so sharing:

Register handlers:

if(Capabilities.cpuArchitecture=="ARM")
{
	NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, handleActivate, false, 0, true);
	NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, handleDeactivate, false, 0, true);
	NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleKeys, false, 0, true);
}

Define handlers:

private function handleActivate(event:Event):void
{
	NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
}
 
private function handleDeactivate(event:Event):void
{
	NativeApplication.nativeApplication.exit();
}
 
private function handleKeys(event:KeyboardEvent):void
{
	if(event.keyCode == Keyboard.BACK)
	NativeApplication.nativeApplication.exit();
}

Good luck!