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
Related
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 need to read sms on it arrive. I get cordova-plugin-sms and use this code. But how i could change this code in order to work in ionic 3?
if(window.SMS){
window.SMS.startWatch(data => {
console.log('watching', 'watching started');
}, error => {
console.log('failed to start watching');
});
}
document.addEventListener('onSMSArrive', function(e) {
var sms = e.data;
console.log(sms);
});
This plugin is not meant to read/receive/listen to SMS.
From the FAQ section of the repo:
How can I receive SMS?
You can't receive SMS via this plugin. This plugin only sends SMS.
There is a major difference between the plugins
cordova-sms-plugin and
cordova-plugin-sms
the last one supports receiving SMS, but not the first
There are some open issues with cordova-plugin-sms and Ionic 3 compatibility.
You can use an alternate plugin cordova-plugin-sms-receive
It has below code that you can use in your app for receiving sms:
Event: onSMSArrive
Triggered when a new SMS has arrived. You need call startWatch() first.
/* Initialize incoming SMS event listener */
document.addEventListener('onSMSArrive', function(e) {
console.log('onSMSArrive()');
var IncomingSMS = e.data;
console.log('sms.address:' + IncomingSMS.address);
console.log('sms.body:' + IncomingSMS.body);
/* Debug received SMS content (JSON) */
console.log(JSON.stringify(IncomingSMS));
});
try with following change-
if((<any>window).SMS){
(<any>window).SMS.startWatch(data => {
console.log('watching', 'watching started');
}, error => {
console.log('failed to start watching');
});
}
(<any>window).addEventListener('onSMSArrive', function(e) {
var sms = e.data;
console.log(sms);
});
I try to pick a contact with cordova plugin contacts, but I still have a bug. My button #pickContact opens correctly the activity where I can tap on a contact. But when I tap on one, nothing happens. When I go back to my page, I have the error message OPERATION_CANCELLED_ERROR (code 6).
I really don't understand where is the problem. I run my app on Android Marshmallow. I thought about a permission problem, but my app can find correctly contacts with navigator.contacts.find, but not with navigator.contacts.pickContact
Here is my code :
function pickContact() {
navigator.contacts.pickContact(function(contact){
alert('ok !');
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
var app = {
// Application Constructor
initialize: function() {
this.onDeviceReady();
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener("deviceready", this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
$("#pickContact").click(pickContact);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
app.initialize();
Thanks for your help !
As per the reference doc of contacts plugin your selected contact will set into JSON.stringify(contact) you can alert it to see which contacts are selected (I have used this plugin but I don't need this function to pick any single contact so not sure if there is any done button or not) then press done or ok button, which will redirect you to your another function where you can get that contacts or fulfill your next requirements.
function pickContact() {
navigator.contacts.pickContact(function(contact){
alert(JSON.stringify(contact));
//This is added by me, on done button click or single selection
setContacts(contact);
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
//This is added by me
function setContacts(ct)
{
alert(JSON.stringify(ct));
$("#contactlist").append(ct);
//or
var getData = JSON.parse(ct);
if(getData.length > 1)
{
for(i=0;i<getData.length;i++)
{
$("#contactlist").append(getData[i]);
}
}
}
Let me know if I am wrong or right.
Thanks a lot for your answer. Unfortunately , your code doesn't works for me, but I found what to do :
When pickcontact opens your native app "contacts", your cordova app is removed on background. On android, that means that you loose the state of your app, and so you have a bug. To solve the problem, you need to add onresume event on your js file, like this :
var app = {
// Application Constructor
initialize: function() {
this.onDeviceReady();
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener("deviceready", this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
$("#pickContact").click(pickContact);
},
onResume: function(resumeEvent) {
//alert('onResume');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
app.initialize();
After that, you can retrieve your picked contact with a function like this :
function pickContact() {
navigator.contacts.pickContact(function(contact){
$("#divTest").append('<p>The following contact has been selected:' + JSON.stringify(contact));
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
So, like everytime in programming, when you know the answer, that's easy. But when you don't know, you loose hours and hours...
I hope that will help someone.
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
});
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.