When we looked at how native code and ActionScript communicate in a native extension, we saw that native code is mostly called and talked to and has a limited number of ways to respond or send data back. These are:
- Returning a FREResult object from a call to FREFunction.
- Using output parameters in a FREFunction.
- Sending an event to ActionScript.
In this article we are focusing on number 3: how events are sent from Java to ActionScript.
Events from Java to ActionScript are asynchronous
We already saw why in the post about events from C to ActionScript, but I’ll repeat it here, as it’s important:
- there isn’t a synchronous way for native code to call an ActionScript function via the AIR Java API the way that ActionScript makes direct calls to native code. When information needs to be sent to ActionScript outside a call that ActionScript initiated, your option is to send an event that ActionScript will receive asynchronously.
- you can send an event to ActionScript form any thread in your native code and it’s delivered on AIR’s single main thread. This is the only AIR Java API call you are allowed to make outside the main thread.
In Java dispatchStatusEventAsync() is a method of the FREContext class, which represents your Extension Context.
public void dispatchStatusEventAsync( String code, String level )
- code is a string, which you set. Use it to identify the event you are sending, for example “SPEECH_RECOGNITION_EVENT”.
- level is another string that you set. Use this to send more detailed information about the event to ActionScript, for example “Speech recognition results” or “No results found”.
How this is received by ActionScript
On the ActionScript side the target of the event is the instance of flash.externalExtensionContext, which was passed to FREDispatchStatusEventAsync. Wondering where it comes from? Read the next section.
The event’s type is flash.events.StatusEvent. You’ll notice that, among other things, StatusEvent has the following two properties:
- code : String
- level : String
See how this maps to the information sent from the Java side?
A call to dispatchStatusEventAsynch() from your Java code:
"This is the message CODE",
"This is the message LEVEL" );
will be received in your ActionScript code in the form of a StatusEvent in a StatusEvent.STATUS handler that you provide:
private var m_extensionContext : flash.external.ExtensionContext;
m_extensionContext.addEventListener( StatusEvent.STATUS, onStatusEvent );
private function onStatusEvent( _event : StatusEvent ) : void
trace( _event.code );
trace( _event.level );
This will print out:
This is the message CODE
This is the message LEVEL
Here’s a definition of Extension Context, if you need a reminder.
Have a look at how events are sent from C to ActionScript.
Next we’ll see what are the Extension Context Initializer and Finalizer.
Then we will see the order of calls for all these initializers and finalizers.
Over to you
Why do you code in Java? No, seriously.