Native android application flow using back button in Adobe Air

A very common issue to be faced while  developing Adobe AIR applications for android is that the back button does not function in its natural way when running a AIR application. For native android applications the back button respects the flow of a application. IE: if you have a popup open or a submodule called in a native android app, pressing the back button will take the application state one step back in a native manner. However in AIR applications pressing the back button tends to bring you out of the application without any notice.

What you need to do as a AIR developer is  to make the back button respect your application design manually. For doing this you need to register a back button handler in your application code which will prevent the default android back button behavior and override it to your own.

Note the code below which creates a popup by user interaction. Then makes the back button close the popup first before coming out of your application. So the first time you press back button, the application will close the popup if its open, and then on second press it exits the application. You can use such a technique in every aspect of your application to greatly enhance user experience.

 

import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.desktop.NativeApplication;
import flash.display.MovieClip;

var popup:MovieClip = null;
var popupButton:SimpleButton = this.btnPop;
popupButton.addEventListener(MouseEvent.CLICK, onclick);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);
function createPopup():void
{
popup = new PopUp();
popup.x =stage.stageWidth/2;
popup.y =stage.stageHeight/2;
addChild(popup);
}

function removePopup():void
{
removeChild(popup);
popup = null;
}

/******************************************/
function onclick(e:MouseEvent):void
{
if(!popup)
createPopup();
}

function onKey(e:KeyboardEvent):void
{
if(e.keyCode == Keyboard.BACK)
{
e.preventDefault();

if(popup) removePopup();
else NativeApplication.nativeApplication.exit();
}
}

 

Natural Back Button Flow

 

Download Source Code

Download APK

1 Comment - Leave a comment
  1. […] Native android application flow using back button in Adobe Air (flashvisions.com) […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*