Previous Page Next Page

4.10. Command-Line Arguments

4.10.1. Capture Command-Line Arguments

4.10.1.1. Problem

You need to capture command-line arguments sent to your application—either at application startup or while the application is running.

4.10.1.2. Solution

Register for the InvokeEvent, and capture command-line arguments passed into your application.

4.10.1.3. Discussion

Whenever an application is started, or an application is called from the command line while it is running, an InvokeEvent will be broadcast. The event handler for this is passed information about the event, including any arguments passed to the application on the command line.

You should register for the InvokeEvent during your application's initialization phase, to ensure that the event is captured when the application is initially launched.

You can register for the event from the NativeApplication singleton, like so:

function init()
{
air.NativeApplication.nativeApplication.addEventListener
(air.InvokeEvent.INVOKE,onInvoke);
}

This registers the onInvoke function as a handler for InvokeEvent. The handler is passed an instance of the InvokeEvent object, which contains a property named arguments which is an Array of Strings of any arguments passed to the application:

function onInvoke(event)
{
    air.trace("onInvoke : " + event.arguments);
}

When testing your application via ADL, you can pass in command-line arguments by using the -- argument. For example:

adl InvokeExample.xml -- foo "bim bam"

This would pass in two arguments to the application: foo and bim bam.

The complete example follows; it listens for the InvokeEvent, and prints out to the included textarea HTML control, as well as the command line via air.trace():

<html>
<head>

    <script src="airaliases.js" />
    <script type="text/javascript">

      function onInvoke(event)
      {
        air.trace("onInvoke : " + event.arguments);

         var field = document.getElementById("outputField");
         field.value += "Invoke : " + event.arguments + "\n";
        }

        function init()
        {
air.NativeApplication.nativeApplication.addEventListener(air.
InvokeEvent.INVOKE,onInvoke);
        }

    </script>

</head>

<body onload="init()">

    <textarea rows="8" cols="40" id="outputField">
    </textarea>

</body>
</html>


					  

Previous Page Next Page