- PhoneGap 4 Mobile Application Development Cookbook
- Zainul Setyo Pamungkas
- 999字
- 2021-07-09 21:26:47
Adjusting the accelerometer sensor update interval
The getCurrentAcceleration
method obtains data from the accelerometer at the time it was called - a single call to obtain a single response object. In this recipe, we'll build an application that allows us to set an interval to obtain a constant update from the accelerometer to detect continual movement from the device.
How to do it…
We will provide additional parameters to a new method available through the PhoneGap API to set the update interval:
- First, create a new PhoneGap project named
accelupdate
. Open Terminal or Command Prompt and run the following command:phonegap create accelupdate com.myapp.accelupdate accelupate
- Add the devices platform. You can choose to use Android, iOS, or both:
cordova platform add ios cordova platform add android
- Add the
device-motion
plugin by running the following command:phonegap plugin add org.apache.cordova.device-motion
- Open
www/index.html
and clean up unnecessary elements; so you have the following:<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <meta name="msapplication-tap-highlight" content="no" /> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <link rel="stylesheet" type="text/css" href="css/index.css" /> <title>Hello World</title> </head> <body> <h1>Accelerometer Data</h1> <div id="accelerometerData">Obtaining data…</div> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript"> </script> </body> </html>
- Below the Cordova JavaScript reference, write a new JavaScript tag block, within which a variable called
watchID
will be declared. - Next, define an event listener to ensure that the device is ready and the native code has loaded before continuing:
<script type="text/javascript"> // The watch id variable is set as a // reference to the current 'watchAcceleration' var watchID = null; // Set the event listener to run // when the device is ready document.addEventListener('deviceready', onDeviceReady, false); </script>
- Now add in the
onDeviceReady
function, which will run a method calledstartWatch
once the native code has fully loaded:// The device is ready so let's // start watching the acceleration function onDeviceReady() { startWatch(); }
- Next, write the
startWatch
function. To do this, first, create a variable calledoptions
to hold the optionalfrequency
parameter, set to 3,000 milliseconds (3 seconds). - Then, set the initial
disabled
properties of two buttons that will allow the user to start and stop the acceleration detection. - Next, assign the
watchAcceleration
to the previously definedwatchID
variable. This will allow you to check for a value or identify if it is still set tonull
. - Apart from defining the success and error function names, you are also sending the
options
variable into the method call, which contains thefrequency
value:// Watch the acceleration at regular // intervals as set by the frequency function startWatch() { // Set the frequency of updates // from the acceleration var options = { frequency: 3000 }; // Set attributes for control buttons document.getElementById('startBtn').disabled = true; document.getElementById('stopBtn').disabled = false; // Assign watchAcceleration to the watchID variable // and pass through the options array watchID = navigator.accelerometer.watchAcceleration( onSuccess, onError, options); }
- With the
startWatch
function written, you now need to provide a method to stop the detection of the acceleration. This firstly checks the value of thewatchID
variable. If this is notnull
, it will stop watching the acceleration using theclearWatch
method, passing in thewatchID
parameter before resetting this variable back tonull
. - Then reference the
accelerometer
div
element and set its value to a user-friendly message. - Next, reassign the
disabled
properties for both the control buttons to allow the user to start watching again, as follows:// Stop watching the acceleration function stopWatch() { if (watchID) { navigator.accelerometer.clearWatch(watchID); watchID = null; var element = document.getElementById('accelerometerData'); element.innerHTML = 'No longer watching your acceleration.'; // Set attributes for control buttons document.getElementById('startBtn').disabled = false; document.getElementById('stopBtn').disabled = true; } }
- Now, create the
onSuccess
method, which will be run after a successful update response. Assign the returned values from theacceleration
object as the HTML within theaccelerometer
div
element for display to the user—the available properties are accessed through theacceleration
object and applied to the string variable:// Run after successful transaction // Let's display the accelerometer data function onSuccess(acceleration) { var element = document.getElementById('accelerometerData'); element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' + 'Acceleration Y: ' + acceleration.y + '<br />' + 'Acceleration Z: ' + acceleration.z + '<br />' + 'Timestamp: ' + acceleration.timestamp + '<br />'; }
- You also need to supply the
onError
method to catch any possible issues with the request. Here, output a user-friendly message, setting it as the value of theaccelerometerData
div
element:// Run if we face an error // obtaining the accelerometer data function onError() { // Handle any errors we may face var element = document.getElementById('accelerometerData'); element.innerHTML = 'Sorry, I was unable to access the acceleration data.'; }
- Finally, add in the two button elements, both of which will have an
onClick
attribute set to eitherstart
orstop
watching the device acceleration:<body> <h1>Accelerometer Data</h1> <button id="startBtn" onclick="startWatch()">start</button> <button id="stopBtn" onclick="stopWatch()">stop</button> <div id="accelerometerData">Obtaining data...</div> </body>
- The results will appear similar to the following screenshot:
- Stopping the acceleration watch will result something like this:
How it works…
By registering an event listener to the deviceready
event, we ensure that the JavaScript code does not run before the native PhoneGap code is executed. Once ready, the application calls the startWatch
function, within which the desired frequency interval for the acceleration updates is set.
The watchAcceleration
method from the PhoneGap API retrieves the device's current acceleration data at the specified interval. If not, as the interval is passed through, it defaults to 10,000 milliseconds (10 seconds). Each time an update has been obtained, the onSuccess
method is run to handle the data as you wish—in this case, displaying the results on the screen.
The watchID
variable contains a reference to the watch
interval and is used to stop the watching process by passing it into the clearWatch
method from the PhoneGap API.
There's more…
In this example, the frequency
value for the accelerometer update interval was set at 3,000 milliseconds (3 seconds). Consider writing a variation on this application that allows the user to manually change the interval value using a slider, or by setting the desired value into an input box.
See also…
- You can check out the official Cordova documentation covering the
watchAcceleration
method and specifying how to obtain accelerometer data at http://plugins.cordova.io/#/package/org.apache.cordova.device-motion.
- JavaScript前端開發模塊化教程
- Oracle WebLogic Server 12c:First Look
- 網頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- Python時間序列預測
- Spring核心技術和案例實戰
- 批調度與網絡問題的組合算法
- PHP+Ajax+jQuery網站開發項目式教程
- 快速入門與進階:Creo 4·0全實例精講
- GitHub入門與實踐
- 深入理解BootLoader
- 從零開始學Unity游戲開發:場景+角色+腳本+交互+體驗+效果+發布
- Android應用程序設計
- Processing開發實戰
- Visual C++網絡編程教程(Visual Studio 2010平臺)
- Python算法交易實戰