Tuesday, April 5, 2011

Working with windows in AIR: Part 10

Today we will learn how to find out whether the user is idle or active while using our application.

Why is this needed? Say, you are making an instant messaging software like MSN Live or Skype, and want to set the user's status to "Busy" or "Away" when he is idle. A user is idle when he doesn't use his mouse or keyboard for a specified amount of time.

To check whether the user is idle, you can listen to the Event.USER_IDLE and Event.USER_PRESENT for the NativeApplication object. For this, you need to create the said object first.

var myApp:NativeApplication = NativeApplication.nativeApplication;

You can set the time that has to pass before calling the user idle.

myApp.idleThreshold = 5;

Now, the listeners and the functions.

myApp.addEventListener(Event.USER_IDLE, onIdle);

function onIdle(Event):void{
trace("Idle!");
}

myApp.addEventListener(Event.USER_PRESENT, onPresent);

function onPresent(Event):void{
trace("Present!");
}

The whole code piece:

var myApp:NativeApplication = NativeApplication.nativeApplication;
myApp.idleThreshold = 5;

myApp.addEventListener(Event.USER_IDLE, onIdle);

function onIdle(Event):void{
trace("Idle!");
}

myApp.addEventListener(Event.USER_PRESENT, onPresent);

function onPresent(Event):void{
trace("Present!");
}

Moreover, we can find out how much time has passed since the user last used his mouse or keyboard. We can do that by referring to the timeSinceLastUserInput of the NativeApplication object:

trace("Time since last input: " + myApp.timeSinceLastUserInput);

Thanks for reading!

Related:

Working with windows in AIR: Part 1
Working with windows in AIR: Part 2
Working with windows in AIR: Part 3
Working with windows in AIR: Part 4
Working with windows in AIR: Part 5
Working with windows in AIR: Part 6
Working with windows in AIR: Part 7
Working with windows in AIR: Part 8
Working with windows in AIR: Part 9
Working with windows in AIR: Part 11
Working with windows in AIR: Part 12

2 comments:

Nemi said...

Thanks, but how to find out if user has been used mouse or keyboard on other apps but not in the application?

Kirill Poletaev said...

It is not possible to do using AS3, but there are workarounds. If the flash is running in a browser, you can use Javascript to capture keyboard events and then dispatch events into the flash.

Post a Comment