I'm trying to send local notifications for every day at 7 am. I have placed the below code in controller,
Code
function send_push_notification (){
cordova.plugins.notification.local.schedule({
id: 10,
title: "Report",
text: "Pls send a report :-)",
firstAt: alarm_time,
at: at_8_am,
every: "day"
}).then(function (success) {
return true;
}, function (err) {
return false
});
}
But it shows ReferenceError: cordova is not defined.. I have defined
<script src="cordova.js"></script> at very first in my app's index.html file.
I also tried the example given in this http://ngcordova.com/docs/plugins/localNotification/ link. But donno which one to follow. Both are totally different.
Update:
cordova.plugins.notification.local.schedule method only works inside deviceready event listener but not in the controller. I should make it to work on controller..
ie, I have a task of sending local push notification when there is no database update made for that particular date else no need for notification.
The following sample code should get you started in sending local notifications in Android and iOS device.
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<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">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<h3>Local Notification</h3>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
index.js
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
try {
cordova.plugins.notification.local.schedule({
text: "This is the text.",
at: new Date(new Date().getTime() + 10000)
});
} catch (e) {
alert("Fail " + e);
}
}
The following sample code sends out a test notification on 10th second after launching the app. The code is tested in Android and iOS devices. The above sample code is available in the github page. You can download the sample app, install notification plugin and test the same.
As suggested in my source, the following command could be used to have a forked and modified push plugin to work in your project:
cordova plugin add https://github.com/zxshinxz/PushPlugin.git
The default push plugin needs to be removed and this will be its replacement. If I understood correctly the post below, this solution fixes local notification usage also when the program is turned off.
More info on that linked post.
My source:
Cordova local notification doesn't work while app is in background
Here is a steps for running local notifications on cordova
Step : 1
Type in cmd prompt of your folder
bower install ngCordova
include in your main index.html file before cordova
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
Step:2
Inject dependency
angular.module('myApp', ['ngCordova'])
Install this plugin
cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications.git
Step:3
Here is schedule.js local notification file used in your controller
(function(){
'use strict';
angular.module('myApp').controller('Schedule',['$scope','$ionicPlatform','$rootScope','$cordovaLocalNotification','$cordovaSms',Schedule]);
function Schedule($scope,$ionicPlatform,$rootScope,$cordovaLocalNotification,$cordovaSms){
//************************Setting Notification***********************
$ionicPlatform.ready(function() {
var now = new Date().getTime();
var _10SecondsFromNow = new Date(now + 10 * 1000);
$cordovaLocalNotification.schedule({
id: 10,
title: 'Report',
text: 'Text here',
at: _10SecondsFromNow
}).then(function (result) {
// ...
});
};
$cordovaLocalNotification.add({
id: 10,
title: 'Report',
text: 'Pls send a report :-)',
firstAt: at_8_am,
every: 'day'
}).then(function (result) {
// ...
});
$scope.scheduleSingleNotification = function () {
$cordovaLocalNotification.schedule({
id: 1,
title: 'Title here',
text: 'Text here',
}).then(function (result) {
// ...
});
};
});
//*******************Notification Ended***********************
})();
Related
I've been trying to learn angularJS, specifically 1.5 using components. My IDE is c9 so the server uses port: process.env.PORT which when I start will show the project at https://projectName-username.c9users.io (with angular-ui-router it has '/#!' on the end). This ide doesn't seem to compile es6 without using something like gulp. So I copy pasted much of the gulp code from the tutorial into my own project so that I could continue using the es6 syntax to build my own project.Everything is working pretty well except I am trying to link bootstrap 4 and my own css files from inside the project rather than a cdn and I can't seem to get the file path correct. When running the gulp file it says serving files from ./build so I tried writing the path from there but it has 404 on the resource.The closest I've come to was no errors thrown trying <link rel="stylesheet" src="#!/src/bower_components/bootstrap/dist/css/bootstrap.min.css"> but checking the network it says it's loading https://billardsWebsite-rawlejuglal.c9users.io/ with type stylesheet but nothing is actually there. Below is my file structure, the index.html file and then the gulpfile. If anyone can enlighten me on how to structure my links to find these resources I would appreciate it.
billardsWebsite
-.c9
-.git
-build
-index.html
-main.js
-node_modules
-src
-bower_components
-boostrap
-dist
-css
-bootstrap.min.css
-js
-css
-styles.css
-index.html
-.bowerrc
-.bower.json
-gulpfile.js
-package.json
-Procfile
Index.html (src/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<title ng-bind="pageTitle"></title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="#!/src/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<div ui-view></div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
gulpfile.js
var gulp = require('gulp');
var notify = require('gulp-notify');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require('babelify');
var ngAnnotate = require('browserify-ngannotate');
var browserSync = require('browser-sync').create();
var rename = require('gulp-rename');
var templateCache = require('gulp-angular-templatecache');
var uglify = require('gulp-uglify');
var merge = require('merge-stream');
// Where our files are located
var jsFiles = "src/js/**/*.js";
var viewFiles = "src/js/**/*.html";
var interceptErrors = function(error) {
var args = Array.prototype.slice.call(arguments);
// Send error to notification center with gulp-notify
notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
// Keep gulp from hanging on this task
this.emit('end');
};
gulp.task('browserify', ['views'], function() {
return browserify('./src/js/app.js')
.transform(babelify, {presets: ["es2015"]})
.transform(ngAnnotate)
.bundle()
.on('error', interceptErrors)
//Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('./build/'));
});
gulp.task('html', function() {
return gulp.src("src/index.html")
.on('error', interceptErrors)
.pipe(gulp.dest('./build/'));
});
gulp.task('views', function() {
return gulp.src(viewFiles)
.pipe(templateCache({
standalone: true
}))
.on('error', interceptErrors)
.pipe(rename("app.templates.js"))
.pipe(gulp.dest('./src/js/config/'));
});
// This task is used for building production ready
// minified JS/CSS files into the dist/ folder
gulp.task('build', ['html', 'browserify'], function() {
var html = gulp.src("build/index.html")
.pipe(gulp.dest('./dist/'));
var js = gulp.src("build/main.js")
.pipe(uglify())
.pipe(gulp.dest('./dist/'));
return merge(html,js);
});
gulp.task('default', ['html', 'browserify'], function() {
browserSync.init(['./build/**/**.**'], {
server: "./build",
port: process.env.PORT || '3000',
notify: false,
ui: {
port: 3001
}
});
gulp.watch("src/index.html", ['html']);
gulp.watch(viewFiles, ['views']);
gulp.watch(jsFiles, ['browserify']);
});
I need to make an application which alert on the user when the user enters a particular geofenced area. I tried cordova geofencing plugin. But it doesn't work when I enter the area. I don't know what is the problem. Here are my codes.
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function () {
// $log.log('Ionic ready');
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if ($window.cordova && $window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if ($window.StatusBar) {
StatusBar.styleDefault();
}
if ($window.geofence) {
$window.geofence.initialize();
$window.geofence.onTransitionReceived = function (geofences) {
// $log.log(geofences);
if (geofences) {
$rootScope.$apply(function () {
geofences.forEach(function (geo) {
geo.notification = geo.notification || {
title: 'Geofence transition',
text: 'Without notification'
};
// toaster.pop('info', geo.notification.title, geo.notification.text);
});
});
}
};
$window.geofence.onNotificationClicked = function (notificationData) {
$log.log(notificationData);
if (notificationData) {
$rootScope.$apply(function () {
// toaster.pop('warning', 'Notification clicked', notificationData.notification.text);
});
}
};
}
});
})
//Entering Zandig
window.geofence.addOrUpdate({
id: "e941166e-2409-4c97-8c80-14ba9e9d71c9",
latitude: 12.958535143383823,
longitude: 77.6381016522646,
radius: 5,
transitionType: 1
}).then(function () {
document.getElementById("notification").innerHTML= "Reached Zandig";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Leaving Trivandrum
window.geofence.addOrUpdate({
id: "1e473337-4747-4ac3-b921-ccaf572f38ce",
latitude: 8.487695348115592,
longitude: 76.95057034492493,
radius: 3,
transitionType: 2
}).then(function () {
document.getElementById("notification").innerHTML= "Left Trivandrum";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Entering 61
window.geofence.addOrUpdate({
id: "8f8119ce-b577-4f22-9880-57333fcff5de",
latitude: 12.9593547,
longitude: 77.63604520000001,
radius: 5,
transitionType: 1
}).then(function () {
document.getElementById("notification").innerHTML= "Entered 61";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Entering Santhi Sagar
window.geofence.addOrUpdate({
id: "d2c08c58-4f31-44e9-8a5c-8baaae3ebee3",
latitude: 12.960690294723518,
longitude: 77.63856634497643,
radius: 15,
transitionType: 1
}).then(function () {
document.getElementById("notification").innerHTML= "Entered Santhi Sagar";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Leaving Santhi Sagar
window.geofence.addOrUpdate({
id: "6923cf7d-470e-4921-9b54-4516c504cba5",
latitude: 12.960690294723518,
longitude: 77.63856634497643,
radius: 15,
transitionType: 2
}).then(function () {
document.getElementById("notification").innerHTML= "Left Santhi Sagar";
console.log('Geofence successfully added');
}, function (reason) {
console.log('Adding geofence failed', reason);
});
//Getting watched from device
window.geofence.getWatched().then(function (geofencesJson) {
var geofences = JSON.parse(geofencesJson);
});
//Listening for Geofencing transitions
window.geofence.onTransitionReceived = function (geofences) {
geofences.forEach(function (geo) {
alert('Geofence transition detected');
console.log('Geofence transition detected', geo);
});
};
//When click on notification
window.geofence.onNotificationClicked = function (notificationData) {
Alert('Geofencing is Working');
console.log('App opened from Geo Notification!', notificationData);
};
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Geofencing</h1>
</ion-header-bar>
<ion-content>
<p id="notification"></p>
</ion-content>
</ion-pane>
</body>
</html>
(In the Github page of the plugin, there was an option that 'unique id for geofence'. I added the unique id from UUID generator online page.)
But no alert is displaying. Can anyone help?
When I run using ionic serve, in the console, the following error found. 'Uncaught TypeError: Cannot read property 'addOrUpdate' of undefined'.
Here is my console errors with device.
0 466310 error Uncaught TypeError: Cannot read property'addOrUpdate' of undefined, htttp://192.168.43.148.8100/js/app.js, Line 28
1 466870 error No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.
2 466930 error Uncaught TypeError: object is not a function, http://192.168.43.148:8100/plugins/cordova/plugin-geofence/www.geofence.js, Line 119
Can anyone help me?
Here is a ionic sample project from authors of same plugin : https://github.com/cowbell/ionic-geofence , in it you can see total guide of how to use it in ionic. Your code should also work but you are doing few mistakes.If you want to run some plugin related code at initialization of application, put them into .run() part, you are using plugin calls out of that. Plus no need to use document.addEventListener('deviceready') as you have $ionicPlatform.ready, initialize plugin in that. Your code will be like this
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
//Use your plugin related calls in this area
})
});
You were getting error of undefined because you were making plugin calls before even their object was available to application.Again, any plugin related calls which you want to run at time of initialization, use them in $ionicPlatform.ready(function() {}) .
so I see you said you tested it using ionic server. you cant test plugins via the browser, you have to actually install it on the device in order to test cordova plugins. You can also test most plugins via emulation using the intel xdk. https://software.intel.com/en-us/intel-xdk just import your project and emulate it then move to your geofenced location via the map on the right. Or you can hit the test tab and push it to a phone and test it using the intel app preview app on your iphone or android device. Last but not least you can use the debug tab to push it straight to a device using a usb cable and this will allow you to have a debugging console while you test the plugin on your device.
I've an app that retrieve server data using ajax. I've tested in localhost, the loader work fine, but when I install my extension and click on the browser action popup, the loader won't show. The little popup delayed for 2 second and shows the result.
popup.html
<div class="cssLoader" ng-show="loader">Fetching...</div>
js
app.controller('MainControl', function($scope, $http){
$scope.loader = true;
$http({
url: "http://www.corsproxy.com/mydomain.net/items.php",
method: "GET",
}).success(function(data) {
$scope.data = data;
$scope.loader = false;
});
});
Without seeing more of your code it is difficult to know for sure. Nonetheless, my suspicion (based upon the fact that your code works outside of the Chrome extension environment but not inside that environment) is that since you're operating in a Chrome Extension environment, you'll need to include the ng-csp directive (see Chrome documentation or Angular documentation).
I developed an Angular app inside a chrome extension and I needed to use ng-csp in order for Angular to load and fully function properly.
Essentially, Chrome extensions (and even more apps) place a number of restrictive security permissions on the browser environment and ng-csp tells Angular to operate in a way that is more consistent with a strict CSP.
I have included an example below that shows loading the entire Angular application properly:
<!DOCTYPE html>
<html ng-app="myApp" ng-csp>
<head>
<meta charset="utf-8">
<title>My Extension</title>
<link href="css/index.css" rel="stylesheet">
<!-- Include in the next line your Angular library code -->
<script type="text/javascript" src="js/angular-lib.js"></script>
<!-- Include in the next line your custom Angular code such as the $http to load the loader -->
<script type="text/javascript" src="js/myapp.js"></script>
</head>
<body>
<!-- Place your HTML code for the 'Fetching' anywhere here in the body -->
</body>
</html>
According to the docs, CSP "is necessary when developing things like Google Chrome Extensions" (more info can be found on the linked page).
Furthermore, besides defining ng-csp on your root element, there is on more crucial point (which affects ngShow/ngHide):
CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically includes some CSS rules (e.g. ngCloak). To make those directives work in CSP mode, include the angular-csp.css manually.
I found this to be necessary only if the angular.js script is defined inside the app's context.
In any case, here is the source code of minimal demo extension that seems to work fine for me:
Structure:
extension-root-dir/
|_____manifest.json
|_____popup.html
|_____popup.js
|_____angular.js
|_____angular-csp.css
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"browser_action": {
"default_title": "Test Extension",
//"default_icon": {
// "19": "img/icon19.png",
// "38": "img/icon38.png"
//},
"default_popup": "popup.html"
}
}
popup.html:
<!DOCTYPE html>
<html>
<head>
<title>Test Extension</title>
<link rel="stylesheet" href="angular-csp.css" />
</head>
<body ng-csp ng-app="myApp" ng-controller="mainCtrl">
<div ng-show="loader">Fetching...</div>
<div ng-hide="loader">{{status}}</div>
<script src="angular.js"></script>
<script src="popup.js"></script>
</body>
</html>
popup.js:
var app = angular.module('myApp', []);
app.controller('mainCtrl', function ($http, $scope) {
$scope.loader = true;
$http({
url: "http://www.corsproxy.com/mydomain.net/items.php",
method: "GET"
}).finally(function () {
$scope.loader = false;
}).then(function (response) {
$scope.data = response.data;
$scope.status = 'Success !';
}, function (response) {
$scope.status = 'ERROR !';
});
});
(BTW, I am using AngularJS v1.2.16.)
I'm developing an app with backbone.js, require.js and Phonegap. I'm having problems accessing the Phonegap api from the Model. My index.html file looks like this:
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link href="topcoat/css/topcoat-mobile-light.min.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
<link href="css/pageslider.css" rel="stylesheet">
<script type="text/javascript" src="cordova.js"></script>
<script data-main="js/app" src="js/require.js"></script>
</head>
<body></body>
</html>
In the initialize function of the router, I'm testing the Phonegap API:
initialize: function() {
window.localStorage.setItem("key", "some bloddy value");
var value = window.localStorage.getItem("key");
console.log('the value is');
console.log(value);
}
This works fine, I can get that the value is set and is retrieved. I also have a logged in status model. This is as follows:
define(function (require) {
"use strict";
var $ = require('jquery'),
Backbone = require('backbone'),
LoginStatus = Backbone.Model.extend({
defaults: {
loggedIn: false,
api_key: null,
user_id: null
},
initialize: function () {
window.localStorage.setItem("key2", "some other value");
var value = window.localStorage.getItem("key2");
console.log('in init, the value is');
console.log(value);
},
});
return {
LoginStatus: LoginStatus
};
});
When I call instantiate model from the initialize function of the router, I get the error:
Uncaught illegal access at file:///android_asset/www/js/app/models/loginstatus.js
How can I access Phonegap api from my models?
You should add an event listener to deviceready event. Inside the listener you should start the backbone router. In that way you start using phonegap API when everything is ready.
document.addEventListener("deviceready", function(){
Backbone.history.start();
}, false);
I am new to phonegap.please le me know what is the process for creating database for a phonegap ANDROID project? I AM USING ECLIPSE-JUNO AND CORDOVA 2.3.0.
The code given in phonegap docs is not working...
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-2.3.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Open Database</p>
</body>
</html>
this is one of the programs i have tried...i get the output whatever is there in d body tag..
My other doubt is where can we see our data that is inserted in the Database.In Android, we view it with help of SQL LITE MANAGER. Do we have something special for PhoneGap???
So,Please guide me through this....
You are just creating a new SQL Lite Database. Use the Database Object to manipulate the data.
Try this code(from official docs)
<!DOCTYPE html>
<html>
<head>
<title>Storage Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
// Populate the database
//
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
// Transaction error callback
//
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Database</p>
</body>
</html>