Building Android Apps : Controlling the Phone with JavaScript (part 3) - Accelerometer
3. Accelerometer
Next, let’s set up Kilo to duplicate the last entry in the list by shaking the phone. Add the following function to the end of kilo.js:
function dupeEntryById(entryId) {
if (entryId == undefined) {
alert('You have to have at least one entry in the list to shake a dupe.');
} else {
db.transaction(
function(transaction) {
transaction.executeSql(
'INSERT INTO entries (date, food, calories, latitude, longitude) ' +
'SELECT date, food, calories, latitude, longitude ' +
'FROM entries WHERE id = ?;',
[entryId],
function() {
refreshEntries();
},
errorHandler
);
}
);
}
}
Now we need to tell the application when to start and stop watching the accelerometer. We’ll set it up to start watching when the Date panel finishes sliding into view and to stop listening when the panel starts sliding out. To do this, we just need to add the following lines to the document ready function in kilo.js:
$('#date').bind('pageAnimationEnd', function(e, info){
if (info.direction == 'in') {
startWatchingShake();
}
});
$('#date').bind('pageAnimationStart', function(e, info){
if (info.direction == 'out') {
stopWatchingShake();
}
});Note:
Technically, we can bind to just one of the page animation events, like so:
$('#date').bind('pageAnimationEnd', function(e, info){
if (info.direction == 'in') {
startWatchingShake();
} else {
stopWatchingShake();
}
});The reason I didn’t do this is that stopWatchingShake() will not be called until after the page animation is complete. Therefore, the accelerometer will be actively watched during the page transition, which can sometimes result in choppy animation.
All that’s left for us to do is write the startWatchingShake() and stopWatchingShake() functions. Add the following functions to the end of kilo.js:
function startWatchingShake() {
var success = function(coords){
var max = 2;
if (Math.abs(coords.x) > max
|| Math.abs(coords.y) > max
|| Math.abs(coords.z) > max) {
var entryId = $('#date ul li:last').data('entryId');
dupeEntryById(entryId);
}
};
var error = function(){};
var options = {};
options.frequency = 100;
sessionStorage.watchId =
navigator.accelerometer.watchAcceleration(success, error, options);
}
function stopWatchingShake() {
navigator.accelerometer.clearWatch(sessionStorage.watchId);
}