<!DOCTYPE html>
<html>
<head>
<title>PhoneGap Back Button Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Call onDeviceReady when PhoneGap is loaded.
//
// At this point, the document has loaded but phonegap-1.2.0.js has not.
// When PhoneGap is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is loaded and it is now safe to call PhoneGap methods
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {alert("back button pressed");
}
</script>
</head>
<body onload="onLoad()">
</body>
</html>
I want to ask if user want to exit from my app, when it click on back button.
I read this example from http://docs.phonegap.com/en/1.2.0/phonegap_events_events.md.html#backbutton
but it is not working...
How can I do to do it?
I SET SOME ALERT IN ONDEVICEREADY FUNCTION, AND I HAVE SEEN THAT IS NEVER FIRED THIS METHOD....SO THE EVENTLISTENERE DEVICEREADY IS NEVER FIRED...WHY?????
Thanks a lot.
It looks like you should definitely see the alert based on your code and your link. However the tutorial is for version 1.2 and you're using version 2.2. You may want to check that for tutorials using the same version. If one doesn't exist then the functionality may have been removed or you'll need to discuss with the Cordova developers about this problem.
If onDeviceReady() is not fired means that PhoneGap is not yet loaded.
Please make sure that your cordova-2.2.0.js file is in the correct location. As per your sample ".html" and "cordova-2.2.0.js" file should be in the same folder
Related
I'm trying to create an app that can run on Android, iOS and Windows Phone using PhoneGap. Currently, I have only phones with Android so I can't know if the problem I'm having exists on iOS and WP.
I tried the notification (alert, beep and vibration) and the camera APIs.
I took the code lines from the Apache Cordova Documentation. I built the app on PhoneGap Built site, scanned the barcode etc. The app is installed and launched perfectly on the phones but nothing is working (for example, when I clicked on the "Vibrate" link, it doesn't vibrate).
The install and all were done by my tutors (I'm in intership), so I guess it's okay for that part.
I checked for the uses-permissions in the AndroidManifest.xml and it's okay.
I've been looking for answers by searching on google, forums etc. but so far, I've found nothing that matches or fixes my issue. That's why I'm posting this message (please don't pay to much attention for language mistake, I'm not an english native speaker).
Thank you in advance for your help.
Edit : 1st phone : Samsung Galaxy Grand Plus (GT-I9060I), Android : 4.4.4. 2nd phone : Samsung Galaxy S5 Prime (SM-G901F), Android : 5.0.2
Using Cordova version 5.0.0. Necessary plugin features have already been added.
Code from the Apache Cordova Documentation for the notifications :
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
// Empty
}
// Show a custom alert
//
function showAlert() {
navigator.notification.alert(
'You are the winner!', // message
'Game Over', // title
'Done' // buttonName
);
}
// Beep three times
//
function playBeep() {
navigator.notification.beep(3);
}
// Vibrate for 2 seconds
//
function vibrate() {
navigator.notification.vibrate(2000);
}
</script>
</head>
<body>
<p>Show Alert</p>
<p>Play Beep</p>
<p>Vibrate</p>
</body>
If you are having cordova version prior to 3.0.0 then you must include plugins manually in config.xml which resides in resources folder.
If cordova version is >= 3.0.0 then you must include these native features via command line.
You need to provide the events such as click, touchend, pagebeforeshow etc. in OnDeviceReady() method. i.e. you have to register listeners to the HTML elements so that they listen to the events.
It seems that I was not using the correct version of the Apache Cordova Documention (5.0.0) but an older version. The following code is taken from the doc and is working only for vibrate(), and once again, nothing is happening for playBeep() and showAlert(). It doesn't make sense.
I also tried the Camera API (from the correct version of the doc) and it's not working either. I really don't understand why it's okay for vibration and not for the other API.
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
console.log(navigator.vibrate);
}
function alertDismissed() {
alert('Dismissed');
}
function showAlert() {
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
}
function playBeep() {
navigator.notification.beep(2);
}
function vibrate() {
navigator.vibrate(3000);
}
</script>
</head>
<body>
<p><a href="#" onclick="showAlert();
return false;">Show Alert</a></p>
<p><a href="#" onclick="playBeep();
return false;">Play Beep</a></p>
<p><a href="#" onclick="vibrate();
return false;">Vibrate</a></p>
</body>
</html>
I'm currently using cordova 3.7.1. In my app I'm not able to detect the hardware back button in my jquery script. I trying out like this:
$(document).ready(function() {
//registering the back button
document.addEventListener("backbutton", onBackKeyDown, false); });
function onBackKeyDown(e) {
alert("back button pressed");//alert if the android back button is pressed
}
But this does not work. I have tried all possibility
I have also tried to get the current URL in the MainActivity.java using
appView.getUrl();
But this does not return the url of the div
If I have a div as #page2 it is not returning the url.
It only returns http://sas.cer.org/index.html. Its is not returning http://sas.cer.org/index.html#page2
I'm also using jquery mobile.
Are there any alternatives for handling the android/hardware back button on the Native or on the Jquery side??
There are two solutions :
1) You need to include cordova.js in script tag in head section in your index html file to make the events and plugins work.
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
You might not be able to see this file in your folder, but the phonegap | cordova command builds it when running on mobile.
2) Modify your code as given here.
Use mobile-specific events for proper functioning of your app.
The following is employed and working great in an app we deploy to cordova and web.
Requireswindow._cordovaNative = true if in cordova.
I left my button handling code in there as example (see "// close menu if open" and other comments), which you need to replace with your code.
Put this somewhere:
let bNH, bakNavHandler = bNH = {
warningOpen: false,
init: function(){
if (window._cordovaNative)
document.addEventListener('backbutton', this.onback, false);
else {
if (!window.performance || performance.navigation.type != 1)
this.preventDefault();
window.onpopstate = this.onback;
}
},
preventDefault: function(e){
window._cordovaNative ?
e.preventDefault() :
window.history.pushState(null, '', window.location.href);
},
onback: function(e){
// close menu if open
if ($('#ekapp_menu_div').css('margin-right') == '-2px'){
bNH.preventDefault(e)
_that.hideMenuDiv();
}
// close modal if open
else if (!bNH.warningOpen && $('#ekapp_modal:visible')[0]){
bNH.preventDefault(e)
_that.closeModal();
}
// prev screen if history
else if (_that.history.length > 1) {
bNH.preventDefault(e)
_that.previousScreen();
}
// show close app warning
else if (!bNH.warningOpen) {
if (window._cordovaNative)
bNH.preventDefault(e);
_that.openModal('Tap back button again to exit app!');
bNH.warningOpen = true;
$('#ekapp_modal_buttons .ekapp_cancel_btn').one('click', function(){
bNH.warningOpen = false;
if (!window._cordovaNative)
bNH.preventDefault();
});
}
}
};
Then in your deviceready (cordova) or doc ready (web) init function do:
bakNavHandler.init();
Read the doc, you have a full example there
You have to listen for the deviceready event, not for document ready
<!DOCTYPE html>
<html>
<head>
<title>Back Button Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
}
</script>
</head>
<body onload="onLoad()">
</body>
</html>
I have started using JQuery in my Phonegap mobile application, and since I have done so I am unable to Capture or Program Back & Menu keys. I have tried all the solutions mentioned here without success.
Currently this is what I have (onload is calling from ):
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
return;
}
function onDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
document.addEventListener("menubutton", onMenuKeyDown, false);
}
function onMenuKeyDown() {
$("#AudioPopup").popup("open");
return;
}
function onBackKeyDown() {
$("#AudioPopup").popup("open");
return;
}
It was working fine before moving to JQuery mobile.
Any help will be appreciated.
Thanks!
AR
I use the following code for dealing with PhoneGap back events inside onDeviceReady:
//handle back button
document.addEventListener("backbutton", function(e) {
if($.mobile.activePage.is('#main',
{ transition: "fade", changeHash: false })){
e.preventDefault();
navigator.app.exitApp();
} else {
location.href='main.html';
}
}, false);
Replace backbutton with menubutton for the menu event. I've also added a JQuery fade transition to smooth out the process as user experience goes. This would also enable you to place the code into the onDeviceReady function, instead of calling it from somewhere else.
Tested with:
jquery-1.8.2;
jquery.mobile-1.2.0;
phonegap-2.8.
Edit:
It seems that now your issue is that of onDeviceReady not triggering when on mobile device environment. I would suggest you try using a deferred object model, such as the one explained here: Correct way of using JQuery-Mobile/Phonegap together?
This could be an issue of both JQM and PG trying to race for initialization and causing conflicts. If it doesn't work, please provide details of how you are dealing with mobileinit
This is what ultimately made my day. And hopefully it should help others as well.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Project</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var dd = $.Deferred();
var jqd = $.Deferred();
$.when(dd, jqd).done(doInit);
</script>
<script src="js/MyOwn.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script type="text/javascript" src="js/cordova.js"></script>
<script type="text/javascript" src="js/cordova-2.6.0.js"></script>
<script type="text/javascript">
$(document).bind('mobileinit', function () {
jqd.resolve();
});
document.addEventListener('deviceready', deviceReady(), false);
function deviceReady() {
dd.resolve();
document.addEventListener("menubutton", function(e) {
e.preventDefault();
MyCustomMenuFunction();
}, false);
document.addEventListener("backbutton", function(e) {
e.preventDefault();
MyCustomBackFunction();
}, false);
onDeviceReady();
}
function doInit() {
onDeviceReady();
}
</script>
<link rel="stylesheet" href="js/jquery.mobile-1.3.2.min.css">
</head>
Two thing to be noted:
- As I am new to this stuff, I was not adding cordova js earlier. After I added cordova-2.6.0.js then only menubutton started working. Whereas backbutton started working after I added cordova.js as well.
- "deviceReady()" works but "deviceReady" doesn't. Don't know why.
i am trying to insert background audio on my first page on a phonegap app. Currently i am testing this on Android 2.2 (on actual phone) but final app is intended for iOS as well
I have used various methods, the only one that had some success is through javascript. I get a very weird behavior (for me at least). Audio plays only if i click on the button and not on page load even though both(button and ready function) call the same function (playAudio) and when the page loads i do get the alert which means that the playAudio function has been successfully called.
1) Do i do something wrong? How can i fix this please? any ideas?
2) why does the < embed > not work on Android (it works just fine as it should on the desktop browser btw). (i have used 2 embeds for testing purposes with different paths, none works on Android) This should be the easiest way to do background audio..
My intention is of course to get rid of the button and have the music to play automatically on page load.
thank you
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/jquery.js"></script>
<script type="text/javascript" src="phonegap.js"></script>
<script>
$(document).ready(function(){
alert('ready');
playAudio('intro.mp3')
});
function playAudio(src) {
alert('func::playAudio(src)');
if (device.platform == 'Android') {
src = '/android_asset/www/' + src;
}
var media = new Media(src, success, error_error);
media.play();
}
function success() {
// ignore
}
function error_error(e) {
alert('great error');
alert(e.message);
}
</script>
</head>
<body>
<div class="container-fluid">
<button id="button" onclick="playAudio('intro.mp3')"></button>
<embed name="introAudio" src="intro.mp3" loop="false" hidden="true" autostart="true">
<embed name="introAudio2" src="/android_asset/www/intro.mp3" loop="false" hidden="true" autostart="true">
</div>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
I was able to use your code and get the audio to play when the page loads without clicking a button. I tested on Android 4.2 and on Android 2.2 and did not have any problems, beside having to remove the alert call in your playAudio function, since the alert() blocks JS execution and stops the call to play media until the dialog is dismissed.
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady(){
console.log("Device is ready.");
playAudio('intro.mp3');
}
function playAudio(src) {
if (device.platform == 'Android') {
src = '/android_asset/www/' + src;
}
var media = new Media(src, success, error_error);
media.play();
}
function success() { console.log("working");} // in your question above,
// you have a comment that causes a missing '}'
function error_error(e) {
alert('great error');
alert(e.message);
}
This code works fine on both devices. As I pointed out above, in the code that you have in the question, your success method is invalid, because the comment hides the closing brace:
function success() { // ignore }
If you were to do
function success() { } then it will work.
Edit: also, the <embed> seemed to work fine for me on both..at least, I guess it did, since the audio was there. What do you mean "it doesn't work?" Do you expect some sort of UI controls or something?
I created notification icon using system notification plugin in android phonegap.But Now I want to call the built-in notification system in the OS(Android,iphone) using android phonegap. please guide me
thanks in advance.
If you're talking about local notification like alerts, confirms... in PhoneGap you need to take a look at PhoneGap API : Notification
If you're talking about notification that are sent from a server to the device you need to take a look a Push Notification tutorials for Android
Which one are you trying to implement ?
You need to use
navigator.notification.alert("")
or
alert("")
to show the notifications.
Using these commands phonegap will will inoke native notifications(Like for Android it will invoke alert dialog).
I tried putting the following code into a html and ran it and I uploaded it in my server and opened the link in my Safari browser in my iPhone and the clicked on Show Confirm and no window popups up!
<!DOCTYPE html>
<html>
<head>
<title>Notification Example</title>
<script type="text/javascript" charset="utf-8" src="http://mobile-web-development-with-phonegap.eclipselabs.org.codespot.com/svn-history/r99/trunk/com.mds.apg/resources/phonegap/js/phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Empty
}
// process the confirmation dialog result
function onConfirm(button) {
alert('You selected button ' + button);
}
// Show a custom confirmation dialog
function showConfirm() {
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
'Restart,Exit' // buttonLabels
);
}
</script>
</head>
<body>
<p>Show Confirm</p>
</body>
</html>