Handle hardware keyboard events in a Flex mobile application

In a mobile application built in Flex, you can detect when the user presses a hardware key on a mobile device. For example, on an Android device you can detect when the user presses the Home button, Back button, or Menu button.

To detect when the user presses a hardware key, create an event handlers for the KEY_UP or KEY_DOWN event. Typically, you attach the event handlers to the application object as defined by the Application, ViewNavigatorApplication, or TabbedViewNavigatorApplication containers.

The Stage object defines the drawing area of a Flex application. Each application has one Stage object. Therefore, an application container is actually a child container of the Stage object.

The Stage.focus property specifies the component that currently has keyboard focus, or contains null if no component has focus. The component with keyboard focus is the one that receives event notification when the user interacts with the keyboard. Therefore, if Stage.focus is set to the application object, the application object’s event handlers are invoked.

On a mobile device, your application can be interrupted by another application. For example, the mobile device can receive a phone call while your application is running, or the user can switch to a different application.  When the user switches back to your application, the Stage.focus property is set to null. Therefore, event handlers assigned to the application object do not respond to the keyboard.

Because the Stage.focus property can be null on a mobile application, listen for keyboard events on the Stage object itself to guarantee that your application recognizes the event. The following example assigns keyboard event handlers to the Stage object:

<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.View1"
    applicationComplete="appCompleteHandler(event);">

    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;

            // Add the hardware key event handlers to the stage.
            protected function appCompleteHandler(event:FlexEvent):void {
                stage.addEventListener("keyDown", handleButtons, false,1);
                stage.addEventListener("keyUp", handleButtons, false, 1);
            }

            // Event handler to handle hardware keyboard keys.
            protected function handleButtons(event:KeyboardEvent):void
            {
                if (event.keyCode == Keyboard.HOME) {
                    // Handle Home button.
                }
                else if (event.keyCode == Keyboard.BACK) {
                    // Hanlde back button.
                }
            }
        ]]>
    </fx:Script>
</s:ViewNavigatorApplication>

 

Stephen Gilson
Flex Doc Team