Windows* 8 Store App – Motion-based app sleep prevention Sample Whitepaper

Lana N. Lindberg, Software Applications Engineer for the Intel® Atom ™ Processor

Download Article


Windows* 8 Store App – Motion-based app sleep prevention Sample Whitepaper [PDF 395KB]

Introduction


With the introduction of mobile devices with touch screen, a number of mobile apps do not require user input such as touch, mouse, or keyboard. This creates challenges for the developers of motion-based apps; one of them being how a device can detect if a motion-based app is in use. The Motion-based app sleep prevention sample is a Windows Store app that demonstrates how to notify the device that the motion-based app is in use by registering notifications from a sensor in the new Windows 8 environment. This app does not require user input, i.e., mouse or touch; thus, the device will enter sleep mode at the scheduled time. The application uses the gyroscope sensor and starts by connecting to the default gyrometer. It reads x, y, z angular velocities and passes the values to the 3D transform. The user can move the device in different directions and observe the image rotation in 3D based on the angular velocities. Constantly changing sensor reading notifies the device that the app is in use.

Basic Lifecycle


The application uses the gyroscope sensor and starts by connecting to the default gyrometer. It reads x, y, z angular velocities and passes the values to the 3D transform. The user can move the tablet in different directions and observe the image rotation in 3D based on the angular velocities. Constantly changing sensor reading notifies the device that the app is in use preventing it from entering sleep mode. displayRequest.RequestActive  is activated to keep the device awake. When no sensor reading is detected, displayRequest.RequestActive  is released, and the device will go to sleep mode at the preset sleep time.

Motion-based app sleep prevention application code and explanation


This Gyroscope app consists of JavaScript* code, HTML, and CSS. JavaScript code starts the app, connects to the default gyrometer, and reads x, y, z angular velocities. CSS sets the width, height, and position of the gyroscope image and loads it. HTML displays x,y,z angular velocities and the animated gyroscope image on the screen.

JavaScript functions


ActivateDisplayLock()

Activate the DisplayRequest prevents the device from entering sleep mode.
Call requestActive to notify Windows the app requires the display to remain on.

// Activate the DisplayRequest prevents the device from entering sleep mode.
// Call requestActive to notify Windows the app requires the display to remain on.
// dispRequest code segment is taken from MSDN
function ActivateDisplayLock() {
if (dispRequest === null) {
        // Activate a display-required request. If successful, the screen is
        // guaranteed not to turn off automatically due to user inactivity.
        dispRequest = new Windows.System.Display.DisplayRequest;
        dispRequest.requestActive();
 
        WinJS.log && WinJS.log("Display request activated",
                                   "sample",
                                   "status");
     }
}

ReleaseDisplayLock()
Release the DisplayRequest lets the device enter sleep mode at the set sleep time.
Call requestRelease to notify Windows the app does not require the display to remain on.

// Release the DisplayRequest lets the device to enter sleep mode in set sleep time.
// Call requestRelease to notify Windows the app does not require the display to   
// remain on.
// dispRequest code segment is taken from MSDN
function ReleaseDisplayLock() {
     if (dispRequest != null) {
         // Deactivate the display request and set the var to null.
         dispRequest.requestRelease();
         dispRequest = null;
 
         WinJS.log && WinJS.log("Display request released",
                                               "sample",
                                               "status");
 
     }
}

onActivated() event
When the Gyroscope app is launched, the activated event is raised. It connects to the default gyrometer, sets the change sensitivity for the gyroscope based on the report interval and registers an event listener on the image.

 app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !==    
    activation.ApplicationExecutionState.terminated) {
            var minimumReportInterval;
            var reportInterval;
            //Connect to the default gyrometer
            gyroscope = Windows.Devices.Sensors.Gyrometer.getDefault();
 
            //Choose a report interval supported by the sensor
            minimumReportInterval = gyroscope.minimumReportInterval;
            reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
            gyroscope.reportInterval = reportInterval;
 
            //Set the event handler
            gyroscope.addEventListener("readingchanged", onDataChangedGyro);
 
            WinJS.UI.processAll();
        }
        args.setPromise(WinJS.UI.processAll());
    }
};

onDataChangedGyro(e)
This function is called each time a gyroscope event is fired by the driver. It reads x, y, z angular velocities and does a 3D transformation of the gyroscope on the screen. Sensors have different sensitivity in different devices; therefore, x,y,z values will not always stay the same when the device is not in use. If the sensor reading is within a threshold value, +/-2.00, the app is not in use and can go to sleep mode; otherwise, the device will be kept active. When the gyroscope is active, “Display Lock is Activated” is output on the screen. When gyroscope is inactive and is ready to activate sleep mode, "Releasing Display Lock" will be output on the screen.

function onDataChangedGyro(e) {
   var reading = e.reading;
   var thresholdVal = 2.00;
 
   document.getElementById('message').innerHTML = "Display Lock is Activated";
 
    // If the sensor reading is +/-2.00 of a current sensor reading, the app is not // in    
    // use and can go to sleep mode. Since this is a gyroscope, x,y,z will be zero +/-
    // threshold in any position at rest.
    if ((x_degrees <= thresholdVal) & (x_degrees >= -thresholdVal) &
        (y_degrees <= thresholdVal) & (y_degrees >= -thresholdVal) &
        (z_degrees <= thresholdVal) & (z_degrees >= -thresholdVal)) {
 
         // Release Display Lock
         ReleaseDisplayLock();   
         document.getElementById('message').innerHTML = "Releasing Display Lock";
    } else {
  // Activate Display Lock
         ActivateDisplayLock();
    }
 
    x_degrees = reading.angularVelocityX.toFixed(2);
    y_degrees = reading.angularVelocityY.toFixed(2);
    z_degrees = reading.angularVelocityZ.toFixed(2);
    id('txtXVelocity').innerHTML = reading.angularVelocityX.toFixed(2);
    id('txtYVelocity').innerHTML = reading.angularVelocityY.toFixed(2);
    id('txtZVelocity').innerHTML = reading.angularVelocityZ.toFixed(2);
 
    id('reportInterval').innerHTML = gyroscope.reportInterval;
 
    id('gyroscope').style.msTransform = 'perspective(0px)
translate3d(100px, 100px, 0px)
rotateX(' + x_degrees + 'deg)
rotateY(' + y_degrees + 'deg)
rotateZ(' + z_degrees + 'deg)';
}

id(elementId)
This function is invoked within onDataChanged to retrieve the given identifier from the HTML document.

function id(elementId) {
    return document.getElementById(elementId);
}

app.start()
Starts the application.

CSS functions


In CSS we load the gyroscope image and set its width, height, and position.

#gyroscope {
   width: 900px;
   height: 506px;
   background-image: url(../images/gyroscope.png);
   position: absolute;
}

HTML functions


In HTML we output x, y, z, velocity values for the Gyroscope.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Motion-based app sleep prevention</title>
 
    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
 
     <!-- Gyroscope references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script type = "text/javascript" src="/js/default.js"></script>
</head>
<body role="application">
    <header aria-label="Header content" role="banner">
        <h1 style="margin-bottom: 100px;">
            <span class="pagetitle" style="position: absolute; left: 260px; top: 30px">Motion-based app sleep prevention </span>
        </h1>
        <h2>
            <span class="pagetitle" style="position: absolute; left: 580px; top: 100px">(Gyroscope)</span>
        </h2>        <button class="win-backbutton" style="position: absolute; right: 50px; top: 20px" aria-label="Back" disabled></button>
    </header>
    <div id="gyroscope_div">
        <table>
            <tr>
                <td>
                    <div class="item" id="gyroscope_status">
                        <br /><br /><br /><br />
                        X: <a id="txtXVelocity">no data</a>
                        <br />
                        Y: <a id="txtYVelocity">no data</a>
                        <br />
                        Z: <a id="txtZVelocity">no data</a>
                        <br /><br />
                        Report Interval: <a id="reportInterval">no data</a>
                        <br />
                       
                    </div>
                </td>
                <td>
                    <canvas id="gyroscope" width="900" height="600"></canvas>
                </td>
            </tr>
 
        </table>
    </div>
</body>
</html>

Conclusion


This sample app demonstrates how a device can detect if a motion-based app is in use by using the gyroscope sensor reading. Constantly changing sensor reading notifies the device that the app is in use preventing it from entering sleep mode. displayRequest.RequestActive  is activated to keep the device awake. When no sensor reading is detected, displayRequest.RequestActive  is released, and the device will go to sleep mode at the preset sleep time.

Helpful Links


  1. Gyroscope, Wikipedia, http://en.wikipedia.org/wiki/Gyroscope
  2. Using Sensors and Location Data for Cutting-edge User Experiences in Mobile Applications, Intel Corporation, http://software.intel.com/en-us/articles/using-sensors-and-location-data-for-cutting-edge-user-experiences-in-mobile-applications
  3. How to keep the display on during audio/video playback (Windows Store apps using JavaScript and HTML) Microsoft Corp, http://msdn.microsoft.com/en-us/library/windows/apps/jj152725
Per informazioni più dettagliate sulle ottimizzazioni basate su compilatore, vedere il nostro Avviso sull'ottimizzazione.