Quick Tip: Detect User Inactivity in a Flash Movie

Quick Tip: Detect User Inactivity in a Flash Movie

Tutorial Details
  • Difficulty: Intermediate
  • Program: Flash
  • Estimated Completion Time: 15 mins

In this Quick Tip, you’ll learn how to detect when the user has been inactive for a determined time. Keep reading to find out how!


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Brief Overview

We’ll detect users interaction using Keyboard and Mouse Events, checking for recent activity using a Timer. We’ll display a message if the determined time has elapsed without activity.


Step 2: Set Up Your Flash File

Launch Flash and create a new Flash Document.

Set the stage size to 550x250px.


Step 3: Interface

This is the interface we’ll be using, a simple background with a message telling the user to wait for five seconds. The following screen will be shown when the five seconds have passed – convert it to MovieClip and mark the Export for ActionScript box. It’s named TheScreen.

Of course this is only one of the many things you can do when the inactivity time passes, GrooveShark for example, pauses the music and shows a message asking the user if he wants to continue using the application. It’s your call to decide what to do.


Step 4: ActionScript

This is the class that does the work, read the comments in the code to find out about its behavior.

package 
{
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;

	public class Main extends Sprite
	{

		private var screen:TheScreen = new TheScreen(); //Creates a new instance of TheScreen
		private var added:Boolean = false; //A boolean to check if the screen has been added to stage

		/* Timer Object */

		private var timer:Timer = new Timer(5000);//Five seconds for this example

		public function Main():void
		{
			timer.start(); //Starts the timer
			timer.addEventListener(TimerEvent.TIMER, showMsg); //Listens for the timer to complete

			/* Mouse and keyboard listeners, stops the timer when a event occurs, if you are using other input method, like the microphone, add its event here */

			stage.addEventListener(MouseEvent.MOUSE_MOVE, stopTimer);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, stopTimer);
			stage.addEventListener(MouseEvent.MOUSE_UP, stopTimer);

			stage.addEventListener(KeyboardEvent.KEY_DOWN, stopTimerK);
			stage.addEventListener(KeyboardEvent.KEY_UP, stopTimerK);
		}

		/* If there is no activity for 5 seconds, a message will display */

		private function showMsg(e:TimerEvent):void
		{
			addChild(screen); //Adds the screen
			added = true;
		}

		/* If there's activity, we clear the message and reset the timer */

		private function stopTimer(e:MouseEvent):void
		{
			if (added)
			{
				removeChild(screen);
				added = false;
			}

			timer.stop();
			timer.start();
		}

		private function stopTimerK(e:KeyboardEvent):void
		{
			if (added)
			{
				removeChild(screen);
				added = false;
			}

			timer.stop();
			timer.start();
		}
	}
}

Step 5: Document Class

Remember to add the class name to the Class field in the Publish section of the Properties panel.


Conclusion

This is a useful and easy way to detect user activity. In this example the activity detected is based in the Mouse and Keyboard events, but you can easily add a Microphone or other input event to meet your needs.

I hope you liked this Quick Tip, thanks for reading!

Tags: Tips
  • http://www.elquefaltaba.es/qborreda.html qborreda

    Nice tip, Carlos.
    Can you actually use just one function for both the MouseEvent and KeyboardEvent events?
    Like this:

    private function stopTimer(e:Event):void

    as you can define it like its a super Event ?

  • Florian

    @qborreda:
    I was thinking the exact same thing!
    I guess in this example it is perfectly possible, since you don’t make use of any type-specific properties / function!

  • http://tahirahmed.wordpress.com Tahir Ahmed

    I like CasaLib’s Inactivity better ..
    http://as3.casalib.org/docs/org_casalib_time_Inactivity.html

    Anyways, its a very good idea and its use is much recommended on CPU-intensive application where you can drop framerate the moment user gets inactive using Event.ACTIVATE on stage along-side.

    - Tahir.

  • http://josecamposcr.blogspot.com/ Jose Campos

    I am building some games and i would like to know how can i detect if the user is focused on my app or anywhere else in the site, i think this is a clue, i think that the CasaLib library might work but i would love any comment to get the best way to detect it!

    Regards!
    Jose Campos
    http://www.jsCampos.com

  • jack

    you also might want to throw in MouseEvent.MOUSE_WHEEL as well…when i was scrolling up and down the page…it told me i went idle…just an idea :)

  • http://pr85.com Pat Reilly

    Could you save a CS3 version of this please?

    • arnold

      Yeah we need CS3 version too,,
      thanks for the tut

      I hope there will be more easy to follow and real world projects tutorials here…
      I only once visit activetuts , so keep it up

  • Luka

    Hi

    This is a great short tip tnx.
    In my example I also added event listener for when user leaves the stage so we know it is not active inside our flash application. :)

    Luka

  • http://leocavalcante.com Leo Cavalcante

    Instead of a “added” boolean var, you can use the “contains” method of the DisplayObjectContainer.

    And instead of timer.stop() and timer.start() you can try the timer.restart().

    About the use of two functions for the same process, qborreda told you the tip.

    ;)

    • http://leocavalcante.com Leo Cavalcante

      Is timer.reset()

  • somdow

    sup all- AS noob here…

    i tried this and although it worked, when i added it to a dummy site im using to try stuff on, it disabled the rest of the stuff i had on the site. like for example, my Full screen command on resize was disabled

    how can i add this to my dummy test site internally and not have it as an external AS file??? or what am i doing wrong?

  • http://www.johnfront.com Ivan Tsankov

    Hello and thanks for the great tut, Carlos!
    But I was wondering if it is possible to build a code where the AS detects if we navigate to a browser tab for example… and then come back and see the paused site.

    Here’s an example:

    http://www.edankwan.com/

    Wait it to load and just navigate to a different browser tab and come back to the site again, you’ll see the page inactive with a message and when clicked, un-pauses.

    Can someone please explain, where to find this script and how it works? Cause I haven’t seen this one for sure.
    Wanna this script so badly!

  • http://www.twitter.com/texasbrat Texasbrat

    Does anyone know if this can be done in AS2? If so how? please share links.

  • Pingback: Quick Tip: Detect User Inactivity in a Flash Movie « GuarniBlog

  • Ravi Babu

    AS2 Code please!