• Handling the Back button in AIR for Android

    by  • September 21, 2014 • Game, Titbits, Tutorials

    Hello everyone, I know a lot of people face issues implementing back button in AIR. Let me tell you something, it’s not your fault. When I was implementing back button for my app Math Operations (Flash Cards), I thought I was doing everything right. And it was working fine to some extent. But it had some glitches. It was driving me nuts, what am I doing wrong. There must be a lot of people facing the same issue so I thought I should write a short tit bit that will help people like me who are struggling with it.

    I will start with my mistake.

    stage.addEventListener(KeyboardEvent.KEY_DOWN, handleBack, false, 0, true);
    
    public function handleBack(e:KeyboardEvent):void 
    {
    	if (KeyboardEvent.KEY_DOWN) {
    		e.preventDefault();
    		e.stopImmediatePropagation();
    		//your desired code
    	}
    }
    

    What I am doing wrong here is I am attaching the event listener to stage. My first thought was it should work, and it worked fine in several cases. While debugging I found some cases it was not listening to the event. I know how frustrated I was, but after few hours of struggle I figured out the issue. And with a small change it worked perfectly. Follow this and you won’t face any issues handling the back button in AIR for Android.

    NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleBack, false, 0, true);
    
    public function handleBack(e:KeyboardEvent):void 
    {
    	if (KeyboardEvent.KEY_DOWN) {
    		e.preventDefault();
    		e.stopImmediatePropagation();
    		//your desired code
    	}
    }
    

    Let me explain in short what’s happening here.
    e.preventDefault(); is preventing the default behavior i.e. to close the application.
    e.stopImmediatePropagation(); stops the event propagation.
    Now only thing left is to write your code and get the desired result.

    I hope this helped you guys. Happy coding!!!

    About

    An accomplished Game Developer with 4 years’ experience covering all aspects of the game development life-cycle including designing, development, testing and maintenance. Have extensive experience in flash based web, desktop and mobile games and other rich internet applications like small websites, software prototypes, portfolios and many more.

    https://plus.google.com/117140375336587355364