How to send push notifications in Flutter android app? - node.js

I developed a flutter android app. and my database is MongoDB. I use Node.js API to connect my flutter app with the MongoDB. I want to send push notifications when a new data record is coming to MongoDB. How can I do that?

The simplest way is to use Firebase Cloud Messaging. Especially since Google is deprecating GCM which was previously used for Android. Also Firebase cloud messaging is free and can be used for both iOS and Android. Apple's APN service will require a setup as well though and a paid developer account.
Create a Firebase project if you haven't already and enable cloud messaging.
To set up your Node.js server so that it can send push notifications to your android and IOS devices. Click on the Project Overview, Settings and service accounts and follow the directions to generate a private key for your project and follow the instructions for setup. Also npm install "firebase-admin".
Once you have firebase setup refer to these docs for how to send messages. https://firebase.google.com/docs/cloud-messaging/send-message
There are several ways to send messages. You can send messages directly.
with this code
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
You can also create topics for devices to subscribe to as well if you are sending out mass notifications. More examples once again are within the docs. Now if you are wondering what the token is that is the next step.
The token comes from the unique device that is connecting to your platform. You can get the token by installing the Firebase Messaging sdk from https://pub.dev/packages/firebase_messaging and following the instructions to add the necessary dependencies to your pubsec.yaml and properly configure your Android manifest and iOS files for the changes.
This package will give you methods to grab your communicate and to receive the notifications that you have sent form your Node.JS server.
Here is an example of grabbing the token from your device on the frontend in flutter.
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
bool _initialized = false;
Future<void> init() async {
if (!_initialized) {
// For iOS request permission first.
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure(onMessage: (Map<String, dynamic> `enter code here`message) {
print('onMessage: $message');
Platform.isAndroid
? showNotification(message['notification'])
: showNotification(message['aps']['alert']);
return;
}, onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
}, onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
return;
});
// For testing purposes print the Firebase Messaging token
String token = await _firebaseMessaging.getToken();
print("FirebaseMessaging token: $token");
_initialized = true;
}
}
At this point you would most likely save the token to your MongoDB database and associate the token with your user and that specific device. Of course you would have to also install the firebase core and for Flutter as well and do all of the necessary configurations.
You are still able to maintain your NodeJS API and MongoDB database and use free cloud messaging service to push your notifications for your server to your device.

Related

Unable to register device to azure notification hub using nodejs packages

We are trying to send push notification dynamically to all registered devices (android) using azure push notification. when we are trying to register the device using device token received from flutter mobile app. it is not getting registered.
For reference: https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-nodejs-push-notification-tutorial
In the above documentation, there is no step to register device using their device token to notification hub. So tried to check on some tech forums and got a sample way to proceed on registering device. Code is below for reference.
notificationHubService.gcm.createTemplateRegistration(
'replacing device token',
'tag', {
'aps': {
'alert': '$(message)',
'badge': '#(count)',
'sound': 'default'
}
},
function (e, r) {
if (e) {
console.log(e);
} else {
console.log({
id: r.RegistrationId,
deviceToken: r.DeviceToken,
expires: r.ExpirationTime
});
}
}
);
Response
{
id: '1294571364808236565-5460521645299605787-1',
deviceToken: undefined,
expires: '9999-12-31T23:59:59.999'
}
device token is always returning as undefined.
Please refer to this sample of how to use the Azure-SB SDK here.
Using this example, you can set the GCM_REGISTRATION_ID which is the device token from the Android device such as you would get from here.
This has the usage of GCM/Firebase here in registering, which is using the REST-API method of create registration under the covers: Create a registration | Microsoft Docs

Push notifications from c# backend through Azure are sent using GCM and not FCM

I created an app in Xamarin.Forms (Android + iOS) I want to send push notifications to.
My goal is to send single notifications from a backend c# desktop application, and have my notifications pushed to both Android and iOS devices.
To do this I'm going to use Azure Notification Hubs.
In the first stage I'm focusing on pushing notificatins to Android devices, so I followed these steps:
I created a Firebase account and registered my application.
I added code to receive notifications in my app.
I created an Azure account.
I created a Notification Hub in Azure.
I inserted my server key in GCM/FCM settings.
I created my backend.
Backend code:
private async void Send()
{
var msg = "Test message " + DateTime.Now.ToLongTimeString();
var url = "http://www.google.com";
string notificationHubName = "MyNotificationHub";
string notificationHubConnection = "Endpoint=sb://xxxxxxx.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=xxxxxxxxxxx";
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
Dictionary<string, string> templateParams = new Dictionary<string, string>();
templateParams["messageParam"] = msg;
templateParams["urlParam"] = url;
try
{
var result = await hub.SendTemplateNotificationAsync(templateParams);
MessageBox.Show(this, "OK.", "Test message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(this, "Exception: " + ex.Message + "." , "Test Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This code is working and notifications are pushed to my Android devices.
Unfortunately, it seems that Azure still uses GCM instead of FCM to deliver notifications.
I received the following mail from Google:
Final reminder: Upgrade GCM to Firebase Cloud Messaging by May 29
Hi Roberto, You are receiving this message because you are an owner of a Firebase project that sent a message via the Google Cloud Messaging (GCM) endpoint in the last 28 days. Last year we announced that the GCM server and client APIs are deprecated. To prevent a disruption in your service, you must redirect your Cloud Messaging server requests to the Firebase Cloud Messaging (FCM) endpoint at fcm.googleapis.com/fcm/ before May 29, 2019.
We also recommend that you upgrade your client SDKs from GCM to the latest version of Firebase Cloud Messaging. Although existing app installations that use GCM methods will continue to function, GCM methods will not work when your app targets future Android versions (after Android Q).
What do I need to do?
The project listed below has used GCM in the past month. To continue sending messages for this project, update server endpoints and upgrade any apps associated with this project to the FCM SDK. In some cases, the endpoints below may be hostnames that were previously deprecated. However, you should still migrate away from them by May 29, 2019.
• GXXXXXXXXXApp (gXXXXXXXXXapp): about 76 requests to android.googleapis.com in the past 28 days
Moreover, if I try to send a test message from Azure portal, this is the result:
I'm worried that after May 29 my app will stop receiving notification.
How can I force FCM instead of GCM?
Thank you!

Push notifications using Firebase Cloud Function iOS

Trying to send remote push notifications through firebase cloud functions. Resources I've been following achieves this through sendToDevice method, which takes a String as an argument. A resource from GitHub says its a "device notification token" that is retrieved when user agrees to receive notifications in app. Firebase says its a "registration token that comes from the client FCM SDKs". What should be the input here, and how to I retrieve it?
// Send notification to device via firebase cloud messaging.
// https://firebase.google.com/docs/cloud-messaging/admin/send-messages
// https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js
//
admin.messaging().sendToDevice(request.query.tokenId, payload).then(response => {
response.results.forEach((result, index) => {
const error = result.error
if (error) {
console.log("Failure sending notification.")
}
});
});
You need to integrate FCM into your iOS app. Pay attention to the part about receiving the current registration token.
Registration tokens are delivered via the FIRMessagingDelegate method
messaging:didReceiveRegistrationToken:. This method is called
generally once per app start with an FCM token. When this method is
called, it is the ideal time to:
If the registration token is new, send it to your application server (it's recommended to implement server logic to determine whether the
token is new).
Subscribe the registration token to topics. This is required only for new subscriptions or for situations where the user has
re-installed the app.
So, you'll have to get a hold of this token in your app, store it somewhere that the Cloud Function can get a hold of (traditionally, Realtime Database), and query for it at the time the function runs.

Requesting a New Registration Id and Creating a Tag for the Azure Notification Hub with NodeJs

How to get a new registration Id for the Azure Notification Hub with JavaScript (NodeJS) and how to create the tag afterwards? The tutorial provided by the Azure documentation misses this part - it sends to all devices (null).
https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-nodejs-how-to-use-notification-hubs/
var payload={
alert: 'Hello!'
};
notificationHubService.apns.send(null, payload, function(error){
if(!error){
// notification sent
}
});
Thanks!
The Notification Hub apns object also has a createNativeRegistration(token, tags, options, callback) function.
var token='abcd1234......'; // token from iOS device
var tags = ['mynewtag', 'myoldtag'];
notificationHubService.apns.createNativeRegistration(token, tags, {success:newRegistrationCompleteCallback, error:newRegistrationErrorCallback});
If you are using the npm you can read the source for it since the documentation is pretty incomplete.
If you are using Mobile Services' Node.js backend, see also the documentation for the built-in push apns object, which seems to be using the same library.

How to register devices to Azure Notification Hub from server side(with NodeJS sdk) ?

I am developing a windows phone 8.1 App (RT), I am trying to push notification with Azure Notification Hub. I am able to do it with the client side SDK available. But I want to do the device registration, tagging etc. from the server side. I see a good guide for .Net backend at http://blogs.msdn.com/b/azuremobile/archive/2014/04/08/push-notifications-using-notification-hub-and-net-backend.aspx . I am using NodeJS in the backend server side. Can anyone help me in the same, with a sample code or so.
I want to register devices from server side (iPhone, Android & Windows Phone), actually I have the device tokens available at the servicer side which is sent from the device via API call.
I want to update multiple tags for each devices time to time.
I want to unregister the devices when user request to do so.
I want to send push notification to specific tags, using the template.
The steps to register the device token and sending out the notification using the Notification Hub in node.js are as follows:
Create a Registration ID
Create Registration
Send Notification
This is server side code, once the device token is received. Note that the registration ID, Device Token, Tag and Callback function are required parameters for notificationHubService.apns.send call.
Here is the code snippet:
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('<Hub Name>','<Connection String>');
var payload={
alert: 'Hello!'
};
notificationHubService.createRegistrationId(function(error, registrationId, response){
if(!error){
console.log(response);
console.log(registrationId);
//RegistrationDescription registration = null;
//registration.RegistrationId = registrationId;
//registration.DeviceToken = req.body.token;
notificationHubService.apns.createOrUpdateNativeRegistration(registrationId, req.body.token, req.token.upn, function(error, response){
if(!error){
console.log('Inside : createOrUpdateNativeRegistration' + response);
notificationHubService.apns.send(null, payload, function(error){
if(!error){
// notification sent
console.log('Success: Inside the notification send call to Hub.');
}
});
}
else{
console.log('Error in registering the device with Hub' + error);
}
});
}
else{
console.log('Error in generating the registration Id' + error);
}
});
Look at open source SDK for server side. I've never tried it out, but should be OK because any SDK is just a wrapper for REST API.

Resources