I have a PhoneGap app, that I've set up Pushbots with (in the onDeviceReady event).
The notification:clicked event is working correctly if the application was not running in the background, but if the app is running and it's in use, and the user brings down the notification tab and clicks on a notification, nothing happens.
How can I fire the notification:clicked event when the app is in the foreground?
I want to navigate to a page whenever the user clicks the notification, whether or not the application is running or not.
My index.js file
myApp.run(['$rootScope', function($rootScope) {
document.addEventListener('deviceready', function() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
window.plugins.PushbotsPlugin.initialize(...);
window.plugins.PushbotsPlugin.on("registered", function(token){
console.log("Registration Id:" + token);
});
window.plugins.PushbotsPlugin.getRegistrationId(function(token){
console.log("Registration Id:" + token);
});
// Should be called once app receive the notification
window.plugins.PushbotsPlugin.on("notification:received", function(data){
alert("received:" + JSON.stringify(data));
console.log("received:" + JSON.stringify(data));
});
// Should be called once the notification is clicked
window.plugins.PushbotsPlugin.on("notification:clicked", function(data){
alert("Notification clicked"); only fires when the app is not running
$rootScope.$emit('onNotificationClick', data);
console.log("clicked:" + JSON.stringify(data));
});
}, false);
}]);
I have a $rootScope.onNotificationClick event in my MainAppController. Should I instantiate / pass the Pushbotsplugin to that controller somehow?
you are emitting the event on notification click. So you can handle $on in controller using below code
$rootScoope.$on('onNotificationClick', function (data) {
// handle here.
//need not pass pushBotPlugin
});
Related
I have a database of persons on my server and it contains a group number attribute. I want to send separate notifications for each of the group. Using the following code, it will send a notification to all apps. How do I set or subscribe the app so that it will know that a certain mobile belongs to a certain group? Each of the members needs to login first before accessing the app.
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
console.log('Received Device Ready Event');
console.log('calling setup push');
// Set your iOS Settings
var iosSettings = {};
iosSettings["kOSSettingsKeyAutoPrompt"] = false;
iosSettings["kOSSettingsKeyInAppLaunchURL"] = true;
window.plugins.OneSignal
.startInit("3074529d MY APP ID HERE d5eb61b000")
.handleNotificationReceived(function(jsonData) {
alert("Notification received: \n" + JSON.stringify(jsonData));
console.log('Did I receive a notification: ' + JSON.stringify(jsonData));
})
.handleNotificationOpened(function(jsonData) {
alert("Notification opened: \n" + JSON.stringify(jsonData));
console.log('didOpenRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
})
.inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.InAppAlert)
.iOSSettings(iosSettings)
.endInit();
},
};
When a user subscribes to your app, you can get the OneSignal Player ID of the device and save it to your database.
Anytime after the init call use getPermissionSubscriptionState method to get the Player ID.
Then you can follow OneSignal's Database Integration Guide to associate the player ID with your user's and group number.
Another option is to use OneSignal Tagging Guide documentation to associate devices with groups.
I want to send a push notification from server to an ionic client and show this notification in client like a phone call (mobile device should play a sound and show 'Accept' or 'Reject' buttons with caller information). It should work if mobile app is not running or in background, that's why I decided to use FCM messages.
this.storage.get('firebase_token').then((token) => {
console.log('Orders get firebase token and call register. Token: ' + token);
this.agentService.registerPushNotifications(token, () => {
this.firebase.onNotificationOpen().subscribe((notification) => {
// How to open the app and show the page with a ringtone ??
});
});
});
How can I open the app and show the call page with a ringtone in incoming push notification? Or maybe there is a better way for this kind of feature.
What you are asking for (the same format like a phone call) isn't possible with Ionic. You can however redirect the user to a view inside the application where you ask him to take action.
Take the following example for push notification. In app.components.ts I initialize this function when the platform is ready
initializePushNotifications() {
let pushObject = this.push.init({
android: {
senderID: 'Your ID Here',
icon: 'logo'
},
ios: {
alert: true,
badge: false,
sound: true
},
windows: {}
});
if (!pushObject['error']) {
pushObject.on('registration').subscribe((data: RegistrationEventResponse) => {
// Whatever you want to do
}, err => {
console.log('Couldnt register:', err);
})
pushObject.on('notification').subscribe((data: any) => {
let self = this;
// When the user click the push notification
if (!data.additionalData.foreground) {
switch (data.additionalData.entity_type) {
case 'takeAction':
this.openView(data.additionalData.user_name, data.additionalData.id);
break;
......
}
}
});
pushObject.on('error').subscribe((e: any) => {
console.log(e.message);
});
} else {
console.error(pushObject);
}
}
See, in the pushed message we add an object under the key additionalData where you can pass whatever you want. You can pass something like entity_type with the value takeAction. When the user click it, you can open a new view and pass additional parameters like the name of the user and the id of the entity or whatever.
On this screen you can open an alert asking the user to click yes or no and based on his input you fire the correct request.
Note
I know this is different from what you were asking for but your request cannot be fulfilled using Ionic.
I try to build an android App with push notification and I want to open a specific component when sur touch a received notification.
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md
http://docs.ionic.io/services/push/
In my app.component.ts constructor I try this :
platform.ready().then(() => {
//StatusBar.styleDefault();
Splashscreen.hide();
this.push.rx.notification()
.subscribe((msg) => {
alert(msg.title + ': ' + msg.text);
console.log(msg.app, "app");
console.log(msg.count, "count");
console.log(msg.image, "image");
console.log(msg.raw, "raw");
console.log(msg.sound, "sound");
console.log(msg.text, "text");
console.log(msg.title, "title");
});
});
It work well when my app isn't close or on pause. I can see my logs.
But when my app is closed or onpause, if I touch notification, my app open but I can't have my logs.
I tried this too :
this.push.on('notification', function(data) {
// do something with the push data
// then call finish to let the OS know we are done
this.push.finish(function() {
console.log("processing of push data is finished");
}, function() {
console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
}, data.additionalData.notId);
});
But I had this error :
Object [object Object] has no method 'on'
What I have to do ?
To have your notification event called when your application isn't in foreground, you have to add content-available: 1 into your push message.
Read this link
I've set up Pushbots to work with my PhoneGap app, but since the setup and initiation of Pushbots is happening in the index.js file, i am not able to call any methods inside my main angularjs controller.
Whenever the user clicks on a notification i would want to run a function from my main controller and navigate to a page.
How can I achieve this?
Here's my index.js file with the onDeviceReady event set up:
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
document.addEventListener("backbutton", onBackKeyDown, false);
window.plugins.PushbotsPlugin.initialize(.....);
window.plugins.PushbotsPlugin.on("registered", function(token){
console.log("Registration Id:" + token);
});
window.plugins.PushbotsPlugin.getRegistrationId(function(token){
console.log("Registration Id:" + token);
});
window.plugins.PushbotsPlugin.on("notification:received", function(data){
console.log("received:" + JSON.stringify(data));
});
// Should be called once the notification is clicked
window.plugins.PushbotsPlugin.on("notification:clicked", function(data){
$scope.LoadMyPage(); //this is not getting fired...
alert("clicked:" + JSON.stringify(data));
console.log("clicked:" + JSON.stringify(data));
});
};
You can use $emit on scope when notification is clicked.
window.plugins.PushbotsPlugin.on("notification:clicked", function(data){
console.log("clicked:" + JSON.stringify(data));
$rootScope.$emit('onNotificationClick');
});
Handle this event in main using
$rootScope.$on('onNotificationClick', function () {
// write your logic here
})
Hope this helps
I have a problem with Ionic framework. I follow the guide to receive and send push notification, but something doesn't work.
When I launch the app, I press button Identify, and show my an alert that say the user ID. After, I press on register button, the phone show me an alert that contains the Device token(ANDROID). But when I go to ionic.io, in the dashboard of my app, the device token there isn't.
If I don't have the token saved on my dashboard, I can't send push notification.
Anyone can help me?
This is my controller.js:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $rootScope, $ionicUser, $ionicPush) {
// Identifies a user with the Ionic User service
$scope.identifyUser = function() {
console.log('Ionic User: Identifying with Ionic User service');
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Add some metadata to your user object.
angular.extend(user, {
name: 'Ionitron',
bio: 'I come from planet Ion'
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
$scope.identified = true;
alert('Identified user ' + user.name + '\n ID ' + user.user_id);
});
};
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
console.log('Got token', data.token, data.platform);
// Do something with the token
});
// Registers a device for push notifications and stores its token
$scope.pushRegister = function() {
console.log('Ionic Push: Registering user');
// Register with the Ionic Push service. All parameters are optional.
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
return true;
}
});
};
// Handles incoming device tokens
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
alert("Successfully registered token " + data.token);
console.log('Ionic Push: Got token ', data.token, data.platform);
$scope.token = data.token;
});
})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
I follow the ionic guide step-by-step
In order to access the token on ionic.io , you have to push it through:
var push = new Ionic.Push();
var user = Ionic.User.current();
var callback = function(pushToken) {
console.log('Registered token:', pushToken.token);
user.addPushToken(pushToken);
user.save(); // you NEED to call a save after you add the token
}
push.register(callback);
as mentioned in the docs.