Missing guide to notifications on your Cordova app

Spread the love

While there’re hundreds of posts which tell you how to set up notifications using the Firebase FCM plugin, there is no post that helps you to take your notifications to production. This post tries to be an end to end guide for being able to setup Firebase notifications on your app.

Setup

As I mentioned above it is fairly easy to do with help from tutorials, setting up a plugin, configuring Firebase and adding google-services.json to your project. I am just adding links to a couple of blog posts which allow you to follow how to install and setup the FCM plugin.

  • http://www.damirscorner.com/blog/posts/20170804-FirebasePushNotificationsInIonicAndCordova.html
  • https://javebratt.com/ionic-push-notification/

If you are working with cordova@7 or above, you will need a workaround to setup, so make sure you check this out for the same.

Setting up and managing tokens

FCM Plugin would generate a token for every device and tokens can be refreshed after some duration. We will handle the token using the getToken and onTokenRefresh method.

FCMPlugin.getToken(token => {
  this.updateToken(token);
});
FCMPlugin.onTokenRefresh(token => {
  this.updateToken(token);
});
updateToken(token) {
  this.storage.get('FCM')
      .then(data => {
        if (data === token) { 
          // Same token
          console.log("Already exists, skipping");
        } else {
          this.backend.updateToken(token)
              .subscribe(data => {
                console.log(data);
                this.storage.set('FCM', token);
              });
        }
     }); 
}

The updateToken function checks whether the token is new and should be sent to your server and finally updates LocalStorage so you don’t send the token next time.
Why are we using getToken when we are checking for token refreshes? Because a token is generated quite early even before your app code is initialized, which means that tokenRefresh method won’t be called for initial cases.

Handling notifications

We write a handler for getting both Foreground and Background notifications, this code should ideally reside in your main.js or app.component.ts if you are using an Angular flavor.

FCMPlugin.onNotification(data => {
    if (data.wasTapped) {
        // Notification was received on device tray and tapped by the user.
        this.nav.setRoot(MyPage, { data: data });
    } else {
        //Notification was received in foreground. Check if we want to do anything here.
    }
});

Sending notifications

Sending a notification with the following parameters in the payload

data = {'id': 3} // JSON containing data to be received by the notification handler
click_action = "FCM_PLUGIN_ACTIVITY" // This is important, this is the code which allows the notification handler to receive the information

Setup icon and color for your notifications

Pick an icon for your notifications, and generate the different sizes needed for the icon. An easy way to generate all required sizes is Android Asset Studio: https://romannurik.github.io/AndroidAssetStudio/
Place your icons in your project, eg in resources/android/ic_notifications
Finally, we need to inform our config.xml to mark these assets to be copied in correct places to be picked by our app.

    <resource-file src="resources/android/ic_notifications/drawable-mdpi/fcm_push_icon.png" target="app/src/main/res/drawable-mdpi/fcm_push_icon.png" />
    <resource-file src="resources/android/ic_notifications/drawable-hdpi/fcm_push_icon.png" target="app/src/main/res/drawable-hdpi/fcm_push_icon.png" />
    <resource-file src="resources/android/ic_notifications/drawable-xhdpi/fcm_push_icon.png" target="app/src/main/res/drawable-xhdpi/fcm_push_icon.png" />
    <resource-file src="resources/android/ic_notifications/drawable-xxhdpi/fcm_push_icon.png" target="app/src/main/res/drawable-xxhdpi/fcm_push_icon.png" />
    <resource-file src="resources/android/ic_notifications/drawable-xxxhdpi/fcm_push_icon.png" target="app/src/main/res/drawable-xxxhdpi/fcm_push_icon.png" />

Finally we can add this information in the payload about what icon and text color needs to be used by the notification.

icon='fcm_push_icon'
color='#33691e'

Handling Firebase tokens in your backend

Firebase tokens can be complex, since there can be multiple use-cases when using these:
– Single user signed in on multiple devices will have multiple tokens
– So will be the case of Token refreshes
– So will be the case of a user re-installing your app.
These can become quite hectic to work with. I used fcm-django in my backend, which helped me simplify things going ahead. The implementation in the library is as follow and I quite like the way they have handled the above scenarios:
– Always create a new token received from user
– There is a nice configuration of disabling multiple tokens from the same user, in case you want to restrict single device usage only.
– Mark token as inactive when sending notification fails rather than trying to find which token is valid from the frontend.
There are some other features provided by the library, do check them out in case you have more use-cases.
I will end with a short snippet to send a notification using fcm-django:

device.send_message(title="Goodbye", icon='fcm_push_icon', color='#33691e', data={'id': '701'}, "click_action":"FCM_PLUGIN_ACTIVITY")

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *