Cordova Phonegap local notifications not working - android

I wanted to first say this is a really nice plugin (https://github.com/katzer/cordova-plugin-local-notifications) but having some difficulties getting it working.
I am using an Android and Phonegap CLI. I have tried both CLI 5.0 and now Phonegap 3.5.0, this is my config.xml:
<preference name="phonegap-version" value="3.5.0" />
In my config.xml I have tried all these combinations:
<plugin name="de.appplant.cordova.plugin.local-notification" spec="0.8.1" source="pgb" />
<gap:plugin name="de.appplant.cordova.plugin.local-notification" />
<plugin name="de.appplant.cordova.plugin.local-notification" source="pgb" />
However the notifications do not appear - nothing happens on the phone - nothing, nada, zilch. I have also downloaded the KitchenSink App (https://github.com/katzer/cordova-plugin-local-notifications/tree/example) and installed on Phonegap build and my phone and nothing again happens..
This is my code on index.html so when the phone fires it should register a local notification asap:
cordova.plugins.notification.local.registerPermission(function (granted) {
// console.log('Permission has been granted: ' + granted);
});
cordova.plugins.notification.local.schedule({
id: 1,
title: 'Reminder',
text: 'Dont forget to pray today.',
every: 'minute',
icon: 'res://icon',
smallIcon: 'res://ic_popup_sync'
});
I also tried
cordova.plugins.notification.local.schedule({
id: 2,
text: "Good morning!",
firstAt: tomorrow_at_8_am,
every: "day" // "minute", "hour", "week", "month", "year"
});
Even the KitchenSink app is not working - nothing happens on the phone??
My Android version is: 5.1.1
How can I get local notifications to appear in Phonegap?

I too have spent many hours trying to get this plugin working & I have, but i do find it to be one of the most temperamental.
Within your js -
var testNotifications = function () {
document.addEventListener("deviceready", function () {
console.warn("testNotifications Started");
// Checks for permission
cordova.plugin.notification.local.hasPermission(function (granted) {
console.warn("Testing permission");
if( granted == false ) {
console.warn("No permission");
// If app doesnt have permission request it
cordova.plugin.notification.local.registerPermission(function (granted) {
console.warn("Ask for permission");
if( granted == true ) {
console.warn("Permission accepted");
// If app is given permission try again
testNotifications();
} else {
alert("We need permission to show you notifications");
}
});
} else {
var pathArray = window.location.pathname.split( "/www/" ),
secondLevelLocation = window.location.protocol +"//"+ pathArray[0],
now = new Date();
console.warn("sending notification");
var isAndroid = false;
if ( device.platform === "Android" ) {
isAndroid = true;
}
cordova.plugin.notification.local.schedule({
id: 9,
title: "Test notification 9",
text: "This is a test notification",
sound: isAndroid ? "file://sounds/notification.mp3" : "file://sounds/notification.caf",
at: new Date( new Date().getTime() + 10 )
// data: { secret:key }
});
}
});
}, false);
};
Now on your html tag -
<button onclick="testNotifications()">Test notification</button>
That should trigger a notification or warn you that it needs permissions
Also top tip is to make sure your notifications are in a folder in the root of the project. android should be mp3 and ios caf

Answer 1 :for version 3.5.0
have a look at plugin's plugin.xml. see line 22
<engine name="cordova" version=">=3.6.0" />
that means plugin only supports version greater than 3.6.0 and you are using 3.5.0
Answer 2 :for version 5.0 or higher
Try the following code as index.html. if it runs perfectly then and other options in to notification.schedule.
as we haven't provided time(at) option notification will triggered immediately.
<html>
<script type="text/javascript" src="cordova.js"></script>
<script>
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
function onDeviceReady() {
cordova.plugins.notification.local.schedule({
id: 1,
title: "Sample Notification",
text: "foo",
every: "week",
data: { meetingId: "123#fg8" }
});
};
</script>
<body>
</body>
</html>

Related

interstitial ad (plugin: admob-free)

My interest is relatively very basic. All I wanted an interstitial banner shows up in some pages of my hybrid application. I indeed appreciate your any comments and guidance since I am a novice developer, a hobbyist only.
I use Adobe PhoneGap build web interface and my "config.xml" is successful to build my apk which works charm.
<preference name="android-build-tool" value="gradle" />
<preference name="phonegap-version" value="cli-7.1.0" />
<plugin name="cordova-plugin-admob-free">
<variable name="ADMOB_APP_ID" value="ca-app-pub-1122334455667788~12345" />
</plugin>
My app is an HTML5 uses Jquery as well.
The index.html page calls following JS files.
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
There is no cordova.js as the phonegap injects during its build, My "js/index.js" file as follows,
var admobid = {}
if (/(android)/i.test(navigator.userAgent)) { // for android & amazon-fireos
admobid = {
banner: 'ca-app-pub-1122334455667788/12345',
interstitial: 'ca-app-pub-1122334455667788/12345',
}
} else if (/(ipod|iphone|ipad)/i.test(navigator.userAgent)) { // for ios
admobid = {
banner: 'ca-app-pub-1122334455667788/12345',
interstitial: 'ca-app-pub-1122334455667788/12345',
}
}
document.addEventListener('deviceready', function() {
admob.banner.config({
id: admobid.banner,
isTesting: true,
autoShow: true,
})
admob.banner.prepare()
admob.interstitial.config({
id: admobid.interstitial,
isTesting: true,
autoShow: true,
})
admob.interstitial.prepare()
document.getElementById('showAd').disabled = true
document.getElementById('showAd').onclick = function() {
admob.interstitial.show()
}
}, false)
document.addEventListener('admob.banner.events.LOAD_FAIL', function(event) {
console.log(event)
})
document.addEventListener('admob.interstitial.events.LOAD_FAIL', function(event) {
console.log(event)
})
document.addEventListener('admob.interstitial.events.LOAD', function(event) {
console.log(event)
document.getElementById('showAd').disabled = false
})
document.addEventListener('admob.interstitial.events.CLOSE', function(event) {
console.log(event)
admob.interstitial.prepare()
})
I build the app successfully but interstitial ads does not appear. (ps. banner does not appear either)
Could you please help me to figure this out? Huge thanks to all of you!
since you are trying to display your ad in testing mode remove
id: admobid.interstitial
and
id: admobid.banner
when you prepare the banner and interstital You need to show them like this :
admob.banner.show();
admob.interstitial.show();

Launch an external app from an App

I am creating an android APP using Ionic framework,I want to launch an external app from my app.
I included the acces-orgin in the config.xml
<access origin="speedtest:*" launch-external="yes"/>
I am using the following code
<button class="button button-positive" ng-click="btnClick()"> Launch Speed Test</button>
In My app.js
function onDeviceReady() {
var scheme;
// Don't forget to add the org.apache.cordova.device plugin!
if(device.platform === 'iOS') {
scheme = 'speedtest://';
}
else if(device.platform === 'Android') {
scheme = 'org.zwanoo.android.speedtest';
}
$scope.btnClick = function() {
appAvailability.check(
scheme, // URI Scheme
function() { // Success callback
window.open('speedtest://', '_system', 'location=no');
console.log('Speedtest is available');
},
function() { // Error callback
//alert("not available");
window.open('https://play.google.com/store/apps/details?id=org.zwanoo.android.speedtest', '_system', 'location=no');
console.log('Speedtest is not available');
}
);
}
}
the following line is not working and it does not throw any error in the console.
window.open('speedtest://', '_system', 'location=no');
Please guide me .
You can start an external application using third party plugin. Please follow the link below
Plugin for check or launch other application in android device
e.g.
Check application for installed
navigator.startApp.check("com.application.name", function(message) { /* success */
console.log(message); // => OK
},
function(error) { /* error */
console.log(error);
});
Start external application
navigator.startApp.start("com.application.name", function(message) { /* success */
console.log(message); // => OK
},
function(error) { /* error */
console.log(error);
});

ngCordova write file on Android

I'm trying to write file to local storage on Android device, using ngCordova function found on ionic forum. This is how the function looks:
$scope.exportClicked = function(options) {
var deferred = $q.defer();
$window.resolveLocalFileSystemURL($window.cordova.file.dataDirectory,
function(dir) {
dir.getFile('text.txt', {
create: true
}, function(fileEntry) {
fileEntry.createWriter(
function(fileWriter) {
if (options['append'] === true) {
fileWriter.seek(fileWriter.length);
}
fileWriter.onwriteend = function(evt) {
evt.fileEntry = fileEntry;
deferred.resolve(evt);
};
fileWriter.write(data);
},
function(error) {
deferred.reject(error);
}
);
}, function(er) {
deferred.reject(error);
});
});
return deferred.promise;
};
When I'm running app through ionic in webbrowser, it gives me an error:
TypeError: Cannot read property 'file' of undefined
at Scope.$scope.exportClicked (app.js:27)
I've installed cordova file plugin, but it looks like it can't find cordova.file functionality.
On Android device it won't work either. Any ideas?
You forgot to install file cordova plugin. https://github.com/apache/cordova-plugin-file
$window.cordova isn't defined. Since you are using ngCordova, and ngCordova has official support for the file plugin, I would start with the ngCordova documentation for the file plugin. Here is the bit you might be interested in:
$cordovaFile.writeFile(cordova.file.dataDirectory, "file.txt", "text", true)
.then(function (success) {
// success
}, function (error) {
// error
});
You also get the added bonus have having more readable code when you use the ngCordova implementation.
If you would rather follow your original example more closely, try replacing $window.cordova with window.cordova, or simply cordova.

Unable to run Contacts plugin on Phonegap / Cordova 3.5.0-0.2.4

Trying to listout Contacts from a android phone using Phonegap / Cordova 3.5.0-0.2.4, installed the "Contacts" plugin to the application folder.
After running below sequence of steps,we just get a default cordova index page displayed on
the device with the message "Connecting to Device"
Its not displaying the contacts which are stored on the mobile.
Kindly help us out.Thanks in advance.
Step1
$ cordova create conto com.example.conto
Step2
$ cordova platform add android
Step3
$ cordova plugin add org.apache.cordova.contacts
Step4
$ cordova plugin list (enter)
org.apache.cordova.contacts 0.2.11 "Contacts"
Step5
Added the following in "app/www/js/index.js"
function read_contacts(){
var options = new ContactFindOptions();
options.filter="";
options.filter="";
options.multiple=true;
var fields = ["*"]; //"*" will return all contact fields
navigator.contacts.find(fields, onSuccess, onError, options);
}
// display the address information for all contacts
function onSuccess(contacts) {
//console.log(JSON.stringify(contacts))
var li = '';
$.each(contacts, function(key, value) {
if(value.name){
$.each(value.name, function(key, value) {
if(key == 'formatted'){
name = value;
}
});
}
if(value.phoneNumbers){
$.each(value.phoneNumbers, function(key, value) {
phone = value.value;
});
}
li += '<li style="text-decoration:none;">'+name+' '+phone+'</li>';
});
$("#contact").html(li);
}
function onError(contactError) {
alert('onError!');
}
Step6:
Added the following in "app/www/index.html"
<ol id="contact"></ol>
Step7
Added the following in app/res/xml/config.xml
<feature name="Contacts">
<param name="android-package" value="org.apache.cordova.contacts.ContactManager" />
</feature>
Step8
Added the following in app/AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Step9
$ cordova run android
On Adroid I tested successfully with onSuccess and fields exchanged, like this:
navigator.contacts.find(onSuccess, onError, fields, options);
Which contradicts the manual but it works.
In the "Developer App" it works as explained in the manual...
Please try to understand the structure of a given application if you are modifying it.
In this case, the 'empty' cordova Project has an app-Object in the index.js, which handles the events and hides the (also given) Splash-Screen.
You simply removed all the code in index.js but left the corresponding elements in index.html.
This is how your index.js should work (based on the default cordova project & your code, untested)
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.openContacts();
},
receivedEvent: function(id) {
console.log('Received Event: ' + id);
},
openContacts:function(){
var options = new ContactFindOptions();
options.filter="";
options.filter="";
options.multiple=true;
var fields = ["*"]; //"*" will return all contact fields
navigator.contacts.find(fields, app.onSuccess, app.onError, options);
},
onSuccess:function(contacts) {
//console.log(JSON.stringify(contacts))
var li = '';
$.each(contacts, function(key, value) {
if(value.name){
$.each(value.name, function(key, value) {
if(key == 'formatted'){
name = value;
}
});
}
if(value.phoneNumbers){
$.each(value.phoneNumbers, function(key, value) {
phone = value.value;
});
}
li += '<li style="text-decoration:none;">'+name+' '+phone+'</li>';
});
$("#contact").html(li);
},
onError:function(contactError) {
alert('onError!');
}
};

PhoneGap Build Push Notification (Android)

I am having trouble receiving any type of callback for the push notifications plugin for phonegap build, I have included the plugin inside config.xml.
I have signed up to GCM and got my project number needed for pushNotification.register().
I also have access to the window.plugins.pushNotification object so I know it's included the plugin.
PhoneGap Build Version: 3.1
Hydration: Disabled
Debug: Enabled
Device: Samsung Tab 2
My index.html js files included are:
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript" src="js/lib/jquery.js" ></script>
<script type="text/javascript" src="js/lib/handlebars.js"></script>
<script type="text/javascript" src="js/handlebars/helpers.js"></script>
<script type="text/javascript" src="js/plugins/fastclick.js"></script>
<script type="text/javascript" src="js/app.js"></script>
My config.xml plugins included are:
// plugins
<gap:plugin name="org.apache.cordova.console" />
<gap:plugin name="org.apache.cordova.device" />
<gap:plugin name="org.apache.cordova.geolocation" />
<gap:plugin name="org.apache.cordova.dialogs" />
<gap:plugin name="org.apache.cordova.inappbrowser" />
<gap:plugin name="org.apache.cordova.splashscreen" />
<gap:plugin name="com.phonegap.plugins.pushplugin" />
// access to external domains
<access origin="*"/>
My app.js call to pushNotification.register()
var app = {
init: function() {
document.addEventListener("deviceready", this.onDeviceReady, false);
},
onDeviceReady: function(){
// DO STUFF
// ....
// ENABLE PUSH
this.push_init();
},
push_init: function(){
app.SENDER_ID = 123456789; // replaced by my actual GCM project no
var pushNotification = window.plugins.pushNotification;
pushNotification.register(
function(){alert('Push: win');}, // never called
function(){alert('Push: Error');}, // never called
{ senderID: app.SENDER_ID, ecb: "app.push_android" }
);
},
// never called
push_android: function(e){
alert('connection established...');
console.log( 'successfully started android' );
console.log( e );
}
};
// start the app
app.init();
After that is called nothing is executed, app.push_android() is a function of app object.
If i don't enter a senderID I get an error saying no sender ID so I know that something is working. This is so frustrating any ideas?
PS - I also noticed something weird, when I console.log the window.plugins.pushNotification it returns an empty object, however I can still call window.plugins.pushNotification.register(), but I thought I would be visible inside the console.log.
I think I've found the solution.
I was passing an integer instead of a string for the property senderID in the object
Doesnt work
pushNotification.register(
function(){alert('Push: win');}, // NOT called
function(){alert('Push: Error');}, // NOT called
{ senderID: 123456789, ecb: "app.push_android" }
);
DOES work
pushNotification.register(
function(){alert('Push: win');}, // called
function(){alert('Push: Error');}, // called
{ senderID: "123456789", ecb: "app.push_android" }
);
Try this push notification code -
var pushNotification;
document.addEventListener('deviceready', onDeviceReady, true);
function onDeviceReady() {
try {
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
pushNotification.register(successHandler, errorHandler, { "senderID": "123456789", "ecb": "onNotificationGCM" }); // required!
}
else {
pushNotification.register(tokenHandler, errorHandler, { "badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN" }); // required!
}
}
catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
alert(txt);
}
};
// handle GCM notifications for Android
function onNotificationGCM(e) {
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
alert(e.regid);
storeToken(e.regid);
}
break;
case 'message':
if (e.foreground) {
var my_media = new Media("beep.wav");
my_media.play();
}
else {
// otherwise we were launched because the user touched a notification in the notification tray.
}
break;
case 'error':
break;
default:
break;
}
}
Refer Link
Refer Devgirl's Weblog

Categories

Resources