Everyday we learn something new and today I learned how to close my Flex App on pressing a Back button on Android devices. You can however change the code to perform a application shut down on a button press from within your mobile application. Because I have to search a lot for this and it wasn’t easy to find an answer so I thought I should write an article and pin point what exactly is required to achieve this.
First thing is to register an event on Application activation. My application is View based so here is what I’ve done
[geshi nums=”1″ highlight=”4]
1 2 3 4 |
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.BAMMAView" width="100%" height="100%" activate="viewnavigatorapplication1_activateHandler(event)"> |
1 |
Now in the viewnavigatorapplication1_activateHandler function add the following code, we are basically registering an event
[geshi lang=”actionscript3″ nums=”1″ target=”_self” ]
1 2 3 4 5 6 7 8 |
protected function viewnavigatorapplication1_activateHandler(event:Event):void { if(Capabilities.cpuArchitecture=="ARM") { NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, handleBKey, false, 0 /*true*/); } } |
and then we write function called handleBKey
[geshi lang=”actionscript3″ nums=”1″ target=”_self” ]
private function handleKeys(event:KeyboardEvent):void
1 2 3 4 |
{ if(event.keyCode == Keyboard.BACK) NativeApplication.nativeApplication.exit(); } |
1 |
1 |
thats it you are done.
This is generally important in many cases where you are compiling your code for both iOS and Android devices and Hardware Back button is something of a pain in many scenarios.
I hope this will help
is this validation for?if(Capabilities.cpuArchitecture
Hi Matt,
This validation is checking that if the target platform is Android. Android devices comes with Back button and Android use ARM architecture.
I hope that’s what you were asking.
Cheers!
why are u using weak reference when adding event listener in that code?
@husin My motive is to show how things could be done. I wrote this as a single view test. A strong reference (default: true) prevents your listener from being garbage-collected. A weak reference does not. So for your actual application you are better off using strong reference and leave the default value (false) intact. Personally I believe using Weak References are sign of slopyness :). If you have anything else to add here please feel free to put in your comments to help other visitors. There is another article that I wrote that could be of some interest to you : http://jaspreetchahal.org/flex-mobile-preventing-the-back-button-event-android/ You may find that useful too.