Wednesday, December 12, 2012

Custom User IDLE Handler - Flex

Its easy to detect user activity in Flex as it provides inbuilt event FlexEvent.IDLE to serve this functionality.
Just need to add,
FlexGlobals.topLevelApplication.systemManager.addEventListener(FlexEvent.IDLE, handleApplicationIdle);
And it works like a charm.

FlexEvent.IDLE keeps dispatched with an idleCounter. Here idleCounter is tick (not milliseconds) and 1 minute = 480 ticks. So if one needs to set idle time for 1 Hr it should be set to 28800 (i.e 480 * 60).
private function handleApplicationIdle(event:TimerEvent):void
{
   if(event.currentTarget.mx_internal::idleCounter == 480) // 1 Minute idle time
   {
 // LOGOUT Process.
   }
}

BUT a drawback is here with the event that when the application browser is minimized or in an inactive browser tab, FlexEvent.IDLE dispatched 5 times slower. Such that if one set idle time 1 Hr, it will be treated as 5 Hr.

To avoid this problem, custom handler can be used.
On application load, add listener for MouseEvent.MOUSE_MOVE and KeyboardEvent.KEY_DOWN.
FlexGlobals.topLevelApplication.systemManager.addEventListener(MouseEvent.MOUSE_MOVE, resetSessionTimer);
FlexGlobals.topLevelApplication.systemManager.addEventListener(KeyboardEvent.KEY_DOWN, resetSessionTimer);
And start a timer with desired timeout value.
sessionTimer = new Timer( ((5)*60*1000), 1);
sessionTimer.start();
sessionTimer.addEventListener(TimerEvent.TIMER_COMPLETE, handleApplicationIdle);
private function resetSessionTimer(event:Event):void
{
 sessionTimer.reset();
 sessionTimer.start();
}
private function handleApplicationIdle(event:TimerEvent):void
{
 // Alert OR LOGOUT Process.
}

This method is more convenient in terms of handling user idle time as the timer always gets reset once user performs an activity event. More event can also be added as per requirement. Once timer reaches to its limit, it performs required logout process. It works perfect without bothering browser window minimized state or inactive state.