A breath of fresh AIR #3: User Idle time

by Sidney de Koning

In AIR you can check the users idle time, meaning that your application can behave differently when the user is not actively using it. On the other side you can also track the time that the user is actively using your application. But what you ask? Let me give you a couple of examples:

– When you are not idle for a period of time, the application syncs with and online database.
– Complex Screensavers – Show full screen for how long the user has been away from its desk ;)
– An Application that warns you when to take breaks because you been sitting way too long behind your computer. The possibilities are endless!

Other fun functions you can use with this is:

timeSinceLastUserInput — The time, in seconds, since the last mouse or keyboard input.
and

idleThreshold – The number of seconds that must elapse without keyboard or mouse input before a presenceChange event is dispatched. By default, the idle threshold is 300 seconds (5 minutes).

import flash.desktop.NativeApplication;
import nl.funkymonkey.firelog.core.*;
var IDLETIME:int = 5;//Yes that is seconds.

initIdleExampleApp();

function initIdleExampleApp():void
{
	NativeApplication.nativeApplication.idleThreshold = IDLETIME;
	NativeApplication.nativeApplication.addEventListener(Event.USER_IDLE, onUserIdle);
	NativeApplication.nativeApplication.addEventListener(Event.USER_PRESENT, onUserPresence);
	Logger.info("Status: Active - status will change if idle for more than " + IDLETIME + " seconds");
}

function onUserIdle(event:Event):void
{
	Logger.info("User has been Idle for at least " + IDLETIME + " seconds".);
	Logger.info("Here you can do what you want.");
}

function onUserPresence(event:Event):void
{
	Logger.info("User is active again, after being idle for " + IDLETIME + " seconds.");
	Logger.info("Now you can make your app get back to its normal state.");
}

What I have noticed with idle time is that the time is an indication and not a real value, it can be a second or two off (this can be caused by the Timer class, as Keith Peters describes here). So keep that in mind.

In my code I trace with FireLog, a simple logger for AIR, and you can find that here.

Here is an example AIR file:
[airbadge]Idle User,http://www.funky-monkey.nl/air/example/idle_screensaver.air,1.0.2[/airbadge]
Have fun coding you own little play things! :)