20 December 2010

Intercept key event on Android

To exit your AIR android application, you need to call
when user press the BACK button

I see a lot of post on blog/forum which give this line of code
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);

I must say it doesn't work on every use case.
For example, when I change screen, I remove my main sprite then add a new sprite.
If I do that, I 'lost' the input focus. I had to touch the screen to give the focus back.
Unless someone could tell me how to give the focus back (post a comment!), the solution is to use this line of code:
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);

EDIT : this works for AS Mobile project only.
You need to make it like this on Flex mobile project.