Monday, 12 August 2013

How to know flex application is idle.

A FlexEvent .IDLE event will dispatch every 100 milliseconds when there has been no keyboard or mouse activity for 1 second.  So, if you want to have some other method fire off after the user is inactive for 5 minutes (for example), you would set it up as detailed below.
Be sure to import the following classes.  IDLE needs to be bound to a SystemManager instance and we will need to reference the mx_internal namespace later on:




import mx.managers.SystemManager;
import mx.events.FlexEvent;
import mx.core.mx_internal;
 
You’ll need to tell Flex that you want to use mx_internal as a namespace to access those properties within the SystemManager class. SytemManager has an “idleCounter” property which is super useful to access- but it is scoped to mx_internal and is not normally accessible. Trying to access it without these steps will throw an error:



use namespace mx_internal;
 
SystemManager is automatically instantiated as a part of every Flex app, so we do not need to do this manually. We will, however, need to add an event listener for FlexEvent.IDLE:


systemManager.addEventListener(FlexEvent.IDLE, userIdle);
 
 
Construct the callback method. Five minutes is equal to 300000 milliseconds… divided by 100 ticks and the number we need to check against is 3000. Of course, you’ll probably want something a little shorter in duration for testing:






private function userIdle(e:FlexEvent):void {
 if(e.currentTarget.mx_internal::idleCounter == 3000){
  //do something!
 }
}
Note that we prefix the idleClounter property with the mx_internal namespace.
That’s it! Now we have a sweet little activity monitor in our app. When activity is detected, idleCounter will automatically reset as well.

No comments: