I have implemented ionic push notification on my app for android. Push notification works well when app is not running(either is in background or not started), however, it does not get status bar notification(notification bar) or vibration that worked when running in background or not started at all.
$ionicPlatform.ready(function() {
localStorage.myPush = ''; // I use a localStorage variable to persist the token
var tokenID = '';
$cordovaPushV5.initialize( // important to initialize with the multidevice structure !!
{
android: {
senderID: "457390407561"
},
ios: {
alert: 'true',
badge: true,
sound: 'false',
clearBadge: true
},
windows: {}
}
).then(function (result) {
$cordovaPushV5.onNotification();
$cordovaPushV5.onError();
$cordovaPushV5.register().then(function (resultreg) {
localStorage.myPush = resultreg;
console.log(localStorage);
}, function (err) {
// handle error
});
});
$rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data){
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
console.log("notification received");
console.log(event);
console.log(data);
console.log(data.message);
console.log(data.title);
console.log(data.count);
console.log(data.sound);
if (data.additionalData.foreground === true) {
// do something if the app is in foreground while receiving to push - handle in app push handling
console.log("notification received in foreground");
}
else {
// handle push messages while app is in background or not started
console.log("notification received in background");
$state.go('app.orderlist');
}
});
// 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);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
Any advice or suggestion?
Thank you in advance.
You can add
forceShow: true
like below
$cordovaPushV5.initialize( // important to initialize with the multidevice structure !!
{
android: {
senderID: "xxxxxxxxx",
forceShow: true
},
ios: {
alert: 'true',
badge: true,
sound: 'false',
clearBadge: true,
},
windows: {}
}
)
Related
I am making a ionic 3 app. I want notifications to appear even when app is in foreground. I have tried using FCM Plugin I'm getting notifications only when app is in background.
Home.ts
import { AngularFireDatabase } from 'angularfire2/database';
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import firebase from 'firebase';
declare var FCMPlugin;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
firestore = firebase.database().ref('/pushtokens');
firemsg = firebase.database().ref('/messages');
constructor(public navCtrl: NavController,public afd:AngularFireDatabase) {
this.tokensetup().then((token)=>{
this.storeToken(token);
})
}
ionViewDidLoad() {
FCMPlugin.onNotification(function (data) {
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert(JSON.stringify(data));
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert(JSON.stringify(data));
}
});
FCMPlugin.onTokenRefresh(function (token) {
alert(token);
});
}
tokensetup(){
var promise = new Promise((resolve,reject)=>{
FCMPlugin.getToken(function(token){
resolve(token);
},(err)=>{
reject(err);
});
})
return promise;
}
storeToken(token){
this.afd.list(this.firestore).push({
uid: firebase.auth().currentUser.uid,
devtoken: token
}).then(()=>{
alert('Token stored')
}).catch(()=>{
alert('Token not stored');
})
// this.afd.list(this.firemsg).push({
// sendername:'adirzoari',
// message: 'hello for checking'
// }).then(()=>{
// alert('Message stored');
// }).catch(()=>{
// alert('message not stored');
// })
}
}
the function cloud for notifications
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var wrotedata;
exports.Pushtrigger = functions.database.ref('/messages/{messageId}').onWrite((event) => {
wrotedata = event.data.val();
admin.database().ref('/pushtokens').orderByChild('uid').once('value').then((alltokens) => {
var rawtokens = alltokens.val();
var tokens = [];
processtokens(rawtokens).then((processedtokens) => {
for (var token of processedtokens) {
tokens.push(token.devtoken);
}
var payload = {
"notification":{
"title":"From" + wrotedata.sendername,
"body":"Msg" + wrotedata.message,
"sound":"default",
},
"data":{
"sendername":wrotedata.sendername,
"message":wrotedata.message
}
}
return admin.messaging().sendToDevice(tokens, payload).then((response) => {
console.log('Pushed notifications');
}).catch((err) => {
console.log(err);
})
})
})
})
function processtokens(rawtokens) {
var promise = new Promise((resolve, reject) => {
var processedtokens = []
for (var token in rawtokens) {
processedtokens.push(rawtokens[token]);
}
resolve(processedtokens);
})
return promise;
}
it works only when the app in the background. but when i exit from the app and it's not in the background I don't get any notification.
You need to edit the FCM Plugin files. I found the solution only for android now.
I use https://github.com/fechanique/cordova-plugin-fcm this FCM plugin for android and ios in cordova.
You need to edit file MyFirebaseMessagingService.java line 53(line no be may be differ).
In this file there is a method onMessageReceived at the end of the method there is a line which is commented, this line calling an another method i.e. sendNotification(....).
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), data);
You have to uncomment this line and change last parameter from remoteMessage.getData() to data (data variable is already there in the code).
And comment this line FCMPlugin.sendPushPayload( data );
Now you are good to go. Now you are able to receive notification even when app is opened (foreground), you will receive the banner (floating) notifications.
If you found anything for IOS please let me know!!!
I am using firebase plugin for ionic 3.
There is a check if notification data contain "notification_foreground" or not and save it in variable foregroundNotification.
if(data.containsKey("notification_foreground")){
foregroundNotification = true;
}
then it create showNotification variable which decide if we need to show notification or not and pass this to the sendMessage (show notification function).
if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) {
boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title));
sendMessage(data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility);
}
your payload should contain notification_foreground, notification_title and notification_body.
I am trying to implement push notifications in Ionic V1 using $cordovaPushV5 but I am not able to get to work. I am able to get the device registration ID but when I test notifications using Firebase Cloud Messaging, it doesnt work. Below is app.js code -
// 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'
// 'starter.controllers' is found in controllers.js
var app = angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, $cordovaPushV5, $rootScope, $cordovaLocalNotification) {
$ionicPlatform.ready(function () {
// hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (cordova.platformId === 'ios' && window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
window.StatusBar.styleLightContent();
}
console.log('app.js');
var options = {
android: {
senderID: "981686413111"
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
};
$cordovaPushV5.initialize(options).then(function (result) {
// start listening for new notifications
$cordovaPushV5.onNotification();
// start listening for errors
$cordovaPushV5.onError();
// register to get registrationId
$cordovaPushV5.register().then(function (registrationId) {
// save `registrationId` somewhere;
console.log(registrationId);
localStorage.setItem('deviceID', registrationId);
}, function (err) {
console.log(err);
});
});
$rootScope.$on('$cordovaPushV5:notificationReceived', function (event, data) {
console.log(data);
});
$rootScope.$on('$cordovaPushV5:errorOccurred', function (event, error) {
console.log("notification error occured");
console.log("event object: ", event);
console.log("error object: ", error);
});
$cordovaPushV5.finish().then(function (result) {
// OK finished - works only with the dev-next version of pushV5.js in ngCordova as of February 8, 2016
}, function (err) {
// handle error
console.log('finish error');
});
//$cordovaPushV5.unregister();
});
});
//# sourceMappingURL=app.js.map
Here is my screenshot of FCM history -
FCM History
I follow the following links to implement -
https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5
What am I missing ?
I'm receiving notifications sent by FCM console even if the app is killed.
Here's my client code:
$ionicPlatform.ready(function() {
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
alert( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
alert( JSON.stringify(data) );
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);
})
The problem is the notification call back is not received. The log data is showing:
View not ready. SAVED NOTIFICATION: javascript:FCMPlugin.onNotificationReceived()
try to put FCMPlugin in
// Ionic Starter App
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordovaOauth'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// 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);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
try{
FCMPlugin.onNotification(
function(data){
console.log('DATA ==>: '+data);
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
console.log('01');
console.log( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
console.log('02');
//alert( JSON.stringify(data));
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);
}catch(e)
{
console.log('in login'+e)
}
});
})
I am trying to set up push notifications with Ionic, mainly by following the official docs: https://docs.ionic.io/services/push/.
However I'm not sure where to call certain bits of code, e.g. $ionicPush.register(). Has anyone come across a recent / up-to-date tutorial that's helpful with this? Tutorials that I've come across use deprecated bits of code, e.g. ionic add.
If you are using Ionic User as well here is the flow I use. These are various functions
$scope.signupForm={};//user object
$scope.beginSignUp=function(){
//sign up
var details = {
'email': $scope.signupForm.email,
'password': $scope.signupForm.pass,
'details':{
'name':$scope.signupForm.dn,
'image':$scope.signupForm.dp
}
}
Ionic.Auth.signup(details).then(signupSuccess, function(err){
});
}
$scope.signupSuccess=function(){
console.log("ionic sign up sucess, now login the user");
var authProvider = 'basic';
var authSettings = { 'remember': true };
var loginDetails = {
'email': $scope.signupForm.email,
'password': $scope.signupForm.pass
};
Ionic.Auth.login(authProvider, authSettings, loginDetails)
.then(authSuccess, function(err){
});
}
function authSuccess(){
console.log("Ionic Login Success ");
var ionic_user = Ionic.User.current();
ionic_user.details.name =$scope.signupForm.dn;
ionic_user.details.image = $scope.signupForm.dp;
ionic_user.save();
registerPush();
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('home', {}, {reload: true});
}
function registerPush(){
console.log("Calling Register Push");
$ionicPush.init({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
Ionic.User.current();
$ionicPush.saveToken(data.token);
//unregister after checking
},
"pluginConfig": {
"ios": {
"badge": true,
"sound": true
},
"android": {
"iconColor": "#FA2B2E",
"senderID": "GCM Project No.",
"icon":"notification"
}
}
});
$ionicPush.register();
}
Use the model signupForm for storing user's email, password etc etc and call beginSignUp() on a button click. Or if it is a login call signupSuccess()
Can we show adMob ads for particular DIV in Android application?
If possible, Can you tell me how to implement?
install this plugin cordova plugin add https://github.com/floatinghotpot/cordova-plugin-admob.git
and past bellow code inside your controller
$(function () {
// alert('1');
if ((/(ipad|iphone|ipod|android|windows phone)/i.test(navigator.userAgent))) {
document.addEventListener('deviceready', initApp, false);
} else {
initApp()
// alert('2');
}
})
function initApp() {
// alert('3');
initAd()
// display the banner at startup
window.plugins.AdMob.createBannerView();
}
function initAd() {
// alert('4');
if (window.plugins && window.plugins.AdMob) {
var ad_units = {
ios: {
banner: 'ca-app-pub-6869992474017983/4806197152',
interstitial: 'ca-app-pub-6869992474017983/7563979554'
},
android: {
banner: 'ca-app-pub-6869992474017983/9375997553',
interstitial: 'ca-app-pub-6869992474017983/1657046752'
},
wp8: {
banner: 'ca-app-pub-6869992474017983/8878394753',
interstitial: 'ca-app-pub-6869992474017983/1355127956'
}
};
var admobid = "";
if (/(android)/i.test(navigator.userAgent)) {
admobid = ad_units.android;
} else if (/(iphone|ipad)/i.test(navigator.userAgent)) {
admobid = ad_units.ios;
} else {
admobid = ad_units.wp8;
}
window.plugins.AdMob.setOptions({
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
bannerAtTop: false, // set to true, to put banner at top
overlap: false, // set to true, to allow banner overlap webview
offsetTopBar: false, // set to true to avoid ios7 status bar overlap
isTesting: true, // receiving test ad
autoShow: true // auto show interstitial ad when loaded
});
// alert('5');
registerAdEvents()
} else {
// alert( 'admob plugin not ready' );
}
}
// optional, in case respond to events
function registerAdEvents() {
document.addEventListener('onReceiveAd', function() {});
document.addEventListener('onFailedToReceiveAd', function(data) {});
document.addEventListener('onPresentAd', function() {});
document.addEventListener('onDismissAd', function() {});
document.addEventListener('onLeaveToAd', function() {});
document.addEventListener('onReceiveInterstitialAd', function() {});
document.addEventListener('onPresentInterstitialAd', function() {});
document.addEventListener('onDismissInterstitialAd', function() {});
// alert('6');
}
function onResize() {
// alert('7');
var msg = 'web view: ' + window.innerWidth + ' x ' + window.innerHeight;
document.getElementById('sizeinfo').innerHTML = msg;
}
// ADMob
})