Closing AIR for Android Applications

Posted on September 17, 2010 | Comments Off

With the different devices out there that do allow for full multitasking by default for all applications it produces a need to be able to programmatically exit applications. The use case I have is I build Flex or ActionScript only applications that get packaged up for devices, usually these are testing applications where I want to have them run for a set time and display some stats. I don’t want to have to force kill the application on the device but want it to exit upon the application being deactivated (basically going into the background). To do this all you need to do is listen for Event.DEACTIVATE firing off the stage, and then exiting the NativeApplication. In code this looks like this:

stage.addEventListener(Event.DEACTIVATE, deactivateHandler);
protected function deactivateHandler(event:Event):void
{
    NativeApplication.nativeApplication.exit();
}

NativeApplication is an AIR only API, and I don’t want to lose the flexibility to test the applications in the browser on the desktop. There are plenty of ways to handle this problem but I am just post a simple and effective process that doesn’t require special versions or builds. I am relying on the assumption that all non desktop devices report their DPI correctly. Here is the bit of code I use to make it easy to test on the desktop and still have it exit on the devices:

public function MyClass()
{
    if (Capabilities.screenDPI > 96)
        stage.addEventListener(Event.DEACTIVATE, deactivateHandler);
}

protected function deactivateHandler(event:Event):void
{
    NativeApplication.nativeApplication.exit();
}