Push Notification Android with ionic framework - android

I'm trying to send push notifications to my Android device from my server. Using plug PushNotification Cordova, my code is something.
var androidConfig = {
"senderID": "inspired-berm-101218",
};
document.addEventListener("deviceready", function(){
$cordovaPush.register(androidConfig).then(function(result) {
// Success
}, function(err) {
// Error
})
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
sessionService.set("token_device",notification.regid);
My information according to me, I followed advice from this forum and tutorials are good and are these:
Api KEY : AIzaSyDtZndyGvmWXF0TpYe83KVDgxRZ4MR3zK8
ID del proyecto: inspired-berm-101218
NĂºmero del proyecto: 805573676421
All this I use both my application and server are the same codes, but nevertheless, I receive the error:
{"multicast_id":7843752850335107662,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
Try uninstalling the application on my phone and reinstall but nothing, does not this work for me.

Use this website to create and run the application again immediately, it gives the exact data.
Google Developers

Related

Detect if Appcelerator app was opened from a push notification

I am trying to determine the best way to detect if my app was opened by tapping on a push notification. I have found some different articles online that suggest different way to do this, but none seem to work in a consistent manner across app platforms and states.
Is there an official Appcelerator way to do this?
Yes, there is an official way.
if (Ti.Platform.getOsname() !== 'android') {
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
});
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types: [
Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
]
});
}
// For Android
else {
var CloudPush = require('ti.cloudpush');
var deviceToken = null;
// Initialize the module
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError
});
// Process incoming push notifications
CloudPush.addEventListener('callback', function (evt) {
receivePush(evt);
});
}
// Process incoming push notifications
function receivePush(e) {
// alert(e.data);
}

Ionic push not working - user not registered

I just had my first contacts with the ionic framework. I've worked with Phonegap and AngularJS before however, so it was not all that new to me.
I found out that there is this new feature to use Google Cloud Messaging push notifications in Ionic, through the Ionic Push feature (http://blog.ionic.io/announcing-ionic-push-alpha/).
Related lines of code from app.js
angular.module('starter', ['ionic','ionic.service.core', 'starter.controllers', 'starter.services'])
.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 && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
// enable push notifications
Ionic.io();
// enable users (http://docs.ionic.io/docs/user-quick-start)
// this will give you a fresh user or the previously saved 'current user'
var user = Ionic.User.current();
// if the user doesn't have an id, you'll need to give it one.
if (!user.id) {
user.id = Ionic.User.anonymousId();
// user.id = 'your-custom-user-id';
}
console.log('user-id:' + user.id);
//persist the user
user.save();
var push = new Ionic.Push({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
}
});
push.register(function(token) {
console.log("Device token:",token.token);
});
push.addTokenToUser(user);
console.log('token added to user');
});
})
Log from ionic serve
ionic $ 0 361081 log Ionic Core:, init
1 361083 log Ionic Core:, searching for cordova.js
2 361085 log Ionic Core:, attempting to mock plugins
3 361155 log user-id:1cc3d21c-b687-4988-b944-ad07b1a677c8
4 361158 log Ionic Push:, a token must be registered before you can add it to a user.
5 361159 log Ionic Push:, token is not a valid Android or iOS registration id. Cannot save to user.
6 361159 log token added to user
7 361160 log Ionic Push:, register
8 361160 error ReferenceError: PushNotification is not defined, http://localhost:8100/lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js, Line: 2
9 361526 log Ionic User:, saved user
Any input is welcome, I am also more than happy to provide more information if needed.
EDIT 10/05/2015:
found out that dev_push = false only works on physical devices, not in browser
I tried to add token to user before even registering the user
I'm having the same problem, seems not many answers online at the moment.
but even on real device, it won't save the token to user.
I just had to decide go live without push first, then use ionic deploy to follow up.
also I think you have to put this line
push.addTokenToUser(user);
inside the register callback according to this doc
http://docs.ionic.io/docs/push-usage
You also need to declare 'ionic.service.push' as a dependency in your angular module if you'd like to use it.
angular.module('starter', ['ionic','ionic.service.core', 'ionic.service.push'])
I have it like this and it works:
Ionic.io();
var user = Ionic.User.current();
if (!user.id) {
user.id = Ionic.User.anonymousId();
// save our newly created user
user.save();
}
var push = new Ionic.Push({});
push.register(function (token) {
console.log("Got Token:", token.token);
// now we have token, so add it to user
push.addTokenToUser(user);
// don't forget to save user to Ionic Platform with our new token
user.save();
});
// set this user as current, so we can acess him later
Ionic.User.current(user);
Did you use this
ionic config set dev_push true-if testing in emulator or laptop
ionic config set dev_pushfalse - if testing on the phone
ionic push --google-api-key Your API Key
ionic config set gcm_key Project Number
Your token is the registration id that is unique for a particular device. That is sent to you by android.
Your Phone (With the API Key)---------> to Google's GCM
Google GCM (recognises it's you via your Project number and API key) -----> Oh it's you let me make a note of it. (Save a token id in it's DB and send's one to you.)
You get a registration id unique for your device(will change if an app is uninstalled).
You call your server say hey it's me your user. Please Notify me if you get something.
Server obliges, says, okay dude, I got this. Saves the registration id with your details probably your username in it's DB.
Now from Server.
I need to inform my users about a great deal(or an accident or something).
Pull up all targeted registration Id's from DB(maybe on some condition)
registrationIds.push(regId) //in a loop
and sender.send(message, registration, function(err, result){
});
Send to Google. Google see's oh only these many people(not all maybe) from this API Key need a notification. no Problem I will notify them and you receive a notification, my dear friend.
As mentioned in the link , Adding token to the $ionicUser is done by doing , user.addPushToken(pushToken); .
For this to work you should first configure the app not to use developement pushes by ,
ionic config set dev_push true
After initialising Ionic.io and Ionic.push , load the user or create one with a new random id ,
Ionic.io();
var push = new Ionic.Push();
Ionic.User.load(localStorage.id).then(function (user) {
Ionic.User.current(user);
pushFactory.register(push, user);
}, function (error) {
/*the user with that id is not present , so create one with a random id and register the push */
});
The push factory is defined as below,
function pushFactory() {
return {
'register': function (push, user) {
push.register(function (pushToken) {
user.addPushToken(pushToken);
user.save().then(function (answer) {
console.log('user saved'+answer);
})
})
}
}
}

android push notification in phone gap not getting notifications

Hi I follow the steps below
1) I created the cordova project structure.
2) I added the platform( android).
3) I added the cordova plugin
cordova plugin add https://github.com/phonegap-build/PushPlugin.git#2.4.0
4) Bulid the cordova project.
5) Next I import the created app in android eclipse(4.4.2)
6) I wrote the code below in index.js file
init: function(){
alert("init");
var pushNotification = window.plugins.pushNotification;
pushNotification.register(successHandler, errorHandler,
{
'senderID':'XXXXXXXXXX',
'ecb':'onNotificationGCM' // callback function
}
);
function successHandler(result) {
console.log('Success: '+ result);
alert(result);
}
function errorHandler(error) {
console.log('Error: '+ error);
}
function onNotificationGCM(e) {
alert("comming");
if('registered' === e.event) {
// Successfully registered device.
}
else if('error' === e.event) {
// Failed to register device.
}
};
I am getting the respose as "OK".and i am not able call 'ecb': onNotificationGCM' // callback function
In Android console I am getting the bellow Message
V/PushPlugin(2512): execute: action=register
V/PushPlugin(2512): execute: data= [{"senderID":"889953963751","ecb":"onNotificationGCM"}] V/PushPlugin(2512): execute: jo={"senderID":"889953963751","ecb":"onNotificationGCM"} V/PushPlugin(2512): execute: ECB=onNotificationGCM senderID=889953963751
09-12 03:13:33.453: D/GCMRegistrar(2512): resetting backoff for com.ensis.hello
09-12 03:13:33.613: V/GCMRegistrar(2512): Registering app com.ensis.hello of senders 889953963751
09-12 W/PluginManager(2512): THREAD WARNING: exec() call to PushPlugin.register blocked the main thread for 181ms. Plugin should use CordovaInterface.getThreadPool().
This is the push notification flow:
your app request a registration to the remote Apple or Google server
if the registration is ok, the remove server returns a token, that identify this specific app on your device
you send this token to your server, saving it (e.g. on a db)
you send a push notification (from your server) calling Apple or Google services with the message and the tokens of the users you want to notify
these services push to your device/app a notification with the message
You must follow all these steps in order to have push notification working.
For android you need to catch the registration id (token) inside the registered event of the notification handler:
function onNotificationGCM(e) {
alert("comming");
if('registered' === e.event) {
// Successfully registered device.
console.log("regID = " + e.regid);
// save/send this registration id on your server
} else if('error' === e.event) {
// Failed to register device.
}
};
For iOS you need to catch it in the succesHandler of the register function.
For more information look at this example in the plugin repository.

How to get Registration ID with Intel XDK?

For a while now, I have been trying to figure out how to send push notifications. The app I have made is for Android right now, but I want to extend it to other devices once I figure this out. I've looked into various services, such as Amazon SNS, but they all neglect to include how to get the device token. They all assume you know how to do that.
So what I am asking is: how do I get a device token/registration ID for a device?
I tried using this code:
var tokenID = "";
document.addEventListener("deviceready", function(){
//Unregister the previous token because it might have become invalid. Unregister everytime app is started.
window.plugins.pushNotification.unregister(successHandler, errorHandler);
if(intel.xdk.device.platform == "Android")
{
//register the user and get token
window.plugins.pushNotification.register(
successHandler,
errorHandler,
{
//senderID is the project ID
"senderID":"",
//callback function that is executed when phone recieves a notification for this app
"ecb":"onNotification"
});
}
else if(intel.xdk.device.platform == "iOS")
{
//register the user and get token
window.plugins.pushNotification.register(
tokenHandler,
errorHandler,
{
//allow application to change badge number
"badge":"true",
//allow application to play notification sound
"sound":"true",
//register callback
"alert":"true",
//callback function name
"ecb":"onNotificationAPN"
});
}
}, false);
//app given permission to receive and display push messages in Android.
function successHandler (result) {
alert('result = ' + result);
}
//app denied permission to receive and display push messages in Android.
function errorHandler (error) {
alert('error = ' + error);
}
//App given permission to receive and display push messages in iOS
function tokenHandler (result) {
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send the token to your server along with user credentials.
alert('device token = ' + result);
tokenID = result;
}
//fired when token is generated, message is received or an error occured.
function onNotification(e)
{
switch( e.event )
{
//app is registered to receive notification
case 'registered':
if(e.regid.length > 0)
{
// Your Android push server needs to know the token before it can push to this device
// here is where you might want to send the token to your server along with user credentials.
alert('registration id = '+e.regid);
tokenID = e.regid;
}
break;
case 'message':
//Do something with the push message. This function is fired when push message is received or if user clicks on the tile.
alert('message = '+e.message+' msgcnt = '+e.msgcnt);
break;
case 'error':
alert('GCM error = '+e.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
}
//callback fired when notification received in iOS
function onNotificationAPN (event)
{
if ( event.alert )
{
//do something with the push message. This function is fired when push message is received or if user clicks on the tile.
alert(event.alert);
}
if ( event.sound )
{
//play notification sound. Ignore when app is in foreground.
var snd = new Media(event.sound);
snd.play();
}
if ( event.badge )
{
//change app icon badge number. If app is in foreground ignore it.
window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
}
}
All I get is an alert that says "result = ok". The alerts later on in the code don't happen. I've tried making sense of the code but I'm not getting anywhere. Any suggestions? Is there a tutorial for this I'm not finding?
Those legacy intel.xdk functions are being retired (the will continue to live in an 01.org, see the notice on this page: https://software.intel.com/en-us/node/492826).
I recommend you investigate one of the many push notification Cordova plugins that are available. Use your favorite web search tool to search for something like "cordova phonegap push notification plugin" to find some. The good ones will have examples of how to use.
Note:-
Unregister - Its not strictly necessary to call it.....
Ensure that you have a sender ID for Android (no idea about iOS).
Result OK means that the plugin is installed correctly and has run properly.
Problems could be due to:
Incorrect sender ID
Testing in emulator without adequate setup
Important - Push notifications are intended for real devices. They are not tested for WP8 Emulator. The registration process will fail on the iOS simulator. Notifications can be made to work on the Android Emulator, however doing so requires installation of some helper libraries, as outlined here, under the section titled "Installing helper libraries and setting up the Emulator".
onNotification must be available as a global object. So try attaching it to the window. Refer to this question
Examples of properly initializing PushPlugin in:
Ionic (my answer)

Trying to implement Pushwoosh on PhoneGap build (Android)

I am trying to get my notifications to work however I am not receiving them. I followed the tutorial for implementing pushwoosh on phonegap build. I have my App ID and API Key from Google however I am not getting my device which the app is on to register when I reinstall the app.
I am guessing that my issue is in the following code:
// handle GCM notifications for Android
function onNotificationGCM(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
PushWoosh.appCode = "YOUR_PUSHWOOSH_APP_ID"; // my pushwoosh id is here
PushWoosh.register(e.regid, function(data) {
alert("PushWoosh register success: " + JSON.stringify(data));
}, function(errorregistration) {
alert("Couldn't register with PushWoosh" + errorregistration);
});
}
break;
I inserted this code in <script> tags within my index file however the device doesn't register what could be causing this issue?
I should also mention that I have the pushwoosh.js file within my javascript folder and I am pointing to it in my reference tags for .js files

Categories

Resources