The stage is now set for us to start enhancing our application with calls
to the native device features. Thanks to phonegap.js,
all you have to do to make the phone vibrate, for example, is to add a bit
of JavaScript to your code:navigator.notification.vibrate();
Pretty simple, right?
1. Beep, Vibrate, and Alert
PhoneGap makes beep, vibrate, and alert functions so simple that
I’m going to lump them together into one example. Specifically, we’ll
set up the app to beep, vibrate, and display a custom alert when the
user creates an entry that puts him over his daily calorie budget. To do
so, add the following function to the end of the
kilo.js located in the ~/Desktop/KiloGap/assets/www/
directory:
function checkBudget() {
var currentDate = sessionStorage.currentDate;
var dailyBudget = localStorage.budget;
db.transaction(
function(transaction) {
transaction.executeSql(
'SELECT SUM(calories) AS currentTotal FROM entries WHERE date = ?;',
[currentDate],
function (transaction, result) {
var currentTotal = result.rows.item(0).currentTotal;
if (currentTotal > dailyBudget) {
var overage = currentTotal - dailyBudget;
var message = 'You are '+overage+' calories over your'
+ 'daily budget. Better start jogging!';
try {
navigator.notification.beep(1);
navigator.notification.vibrate();
} catch(e){
// No equivalent in web app
}
try {
navigator.notification.alert(message,
'Over Budget', 'Dang!');
} catch(e) {
alert(message);
}
}
},
errorHandler
);
}
);
}
Here’s the blow-by-blow description:Let’s examine the four parameters of the
executeSql() method:
Here’s what’s going on in the anonymous function that was passed in as the third
parameter:
With our checkBudget() function
complete, we can now call it by adding a single line to the success
callback of our createEntry() function:
function createEntry() {
var date = sessionStorage.currentDate;
var calories = $('#calories').val();
var food = $('#food').val();
db.transaction(
function(transaction) {
transaction.executeSql(
'INSERT INTO entries (date, calories, food) VALUES (?, ?, ?);',
[date, calories, food],
function(){
refreshEntries();
checkBudget();
jQT.goBack();
},
errorHandler
);
}
);
return false;
}
After you’ve made these changes, save the
kilo.js file, open up a command line and run the following commands to
recompile and install it on your phone (change -d to
-e if you’d like to use the emulator instead):
ant debug
adb -d install -r ~/Desktop/KiloGap/bin/Kilo-debug.apk