Integrating Firebase push notification in Android Application using Ionic

Google from sometime has been unifying all the services it provide under on single dashboard. And I would say that I am a real fan of that concept, as we all know in the current internet space we have to manage and focus on multiple areas and in that if I have to go to multiple platform it is going to drastically reduce my efficiency. Hence, came the Firebase one single platform, to manage everything for your google application and website.

In this blog I am going to focus on integration of fire base cloud messaging (FCM) service in your ionic application. Using FCM you can send push notification to your ionic applications. It pretty simple and straight forward process just follow simple steps as described below and you are good to go.

Step 1

Create your ionic application by executing the following command in your terminal/command prompt(cmd).

 ionic start PushDemo blank

Before you proceed to the next step let’s check and make sure you’re using at least NodeJS Ver. 4.x and npm Ver. 3. You can verify this by simply executing node -v and npm -v in your linux/windows terminal/command prompt(cmd).

Step 2

Now, you ionic application is created and we would like to write the code so that we can receive notification. In order to get the notification we need to configure cloud client in it. The cloud client allows you to interact with our services from your app and is available as npm package. In the directory of your app execute the below mentioned command to install the cloud client package:

npm install @ionic/cloud-angular --save

Before you can configure your cloud settings, you’ll need to have an app ID. In order to get the same in your project directory, run:

$ ionic link

and select create a new app. Now return to the CLI and run ionic linkagain and select the app that you just created. This creates an app in the Dashboard, and sets the generated App ID in your ionic.config.json file.

In your src/app/app.module.ts file:

  • Define a CloudSettings object for your app’s cloud settings. Replace APP_ID with your app’s ID, which you can find in your ionic.config.json file.

Pass your cloud settings into CloudModule.forRoot(), which returns an NgModule (see Angular dependency injection and the Angular Modules guide) with all our providers. This means you don’t have to specify our classes in the providers: array of your components.

import { CloudSettings, CloudModule } from '@ionic/cloud-angular';
const cloudSettings: CloudSettings = { 'core': { 'appid': 'APPID' } };
@NgModule({ declarations: [ ... ], imports: [ IonicModule.forRoot(MyApp), CloudModule.forRoot(cloudSettings) ], bootstrap: [IonicApp], entryComponents: [ ... ], providers: [ ... ] }) export class AppModule {}

Now you’re ready to start using Services.

Step 3

Now to use the Firebase cloud services you would have to set up your account on their portal. By which you can use your credentials in your project. You have to follow this link.

https://console.firebase.google.com

For Android:

  1. First of all sign-in into Firebase console with your google account then go to console and create new project for push notification as sown in below screenshot.

2.   After creating project you will be redirect to next screen where you find your project name and setting icon beside it in the left pane of the window. Click the settings icon and you will be to see your project’s Server key and SenderID under the Cloud Messaging tab as shown in the screen below.

Step 4

Now you have two credential FCM server key and SenderId. After copying it go to the https://apps.ionic.io/login and login in your Ionic account. On dashboard page after login you will see the list of your applications if you have multiple application or a single application if it’s a new account.

Click on the name of the application that we have just created and you will be redirected to your application detail screen. In there from the multiple tabs on the top you need to navigate to “Settings” tab it would look somewhat like the reference image below.

The left window pan will have multiple options there click on the Certificate option and create new security profile. You can name the security profile as you like.Once you have created it go to the edit tag and insert your FCMserver key in next window as shown in below. Leave other parts blank and click on save.

After our configuration in the Firebase console we have got one SENDER_ID we have to bind that SENDER_ID in the project. You can achieve it by executing following command in your project folder.

cordova plugin add phonegap-plugin-push --variable 
SENDER_ID=12341234 --save

Now you have sender id and app id(you will get it after executing ionic link as described above) of your project. Specify both in your projects as shown as below.

const cloudSettings: CloudSettings = {
'core': {
    'app_id': 'APP_ID',
},
'push': {
    'sender_id': 'SENDER_ID',
    'pluginConfig': {
    'ios': {
        'badge': true,
        'sound': true
    },
    'android': {
        'iconColor': '#343434'
    }
    }
}
};

Step 5

Now, import Push from the Cloud Client and specify it as a dependency in your component constructor.

import {Component} from '@angular/core';
import {
Push,
PushToken
} from '@ionic/cloud-angular';

@Component( ... )
export class MyPage {
constructor(public push: Push) {
    ...
}
}

Step 6

Now its time to register your device for fire-base services. In order to do that you have to put following code in your app.component.ts file in app folder.

this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});

Here, we store the generated device token with the current user when the token is saved. If you do not want them associated, you can pass the ignore_useroption. See the saveToken() API docs for more info.

You can un-register a device from push notifications by calling unregister().

To handle push notifications in your app, you need to subscribe to the notification observable. To implement put following function in your app.components.ts file.

this.push.rx.notification()
.subscribe((msg) => {
    alert(msg.title + ': ' + msg.text);
});

You are all setup with the push notification setup. Now, you just have to send them from ionic portal and you can receive notification in your application.

Step 7

To send push notification from your ionic portal you just have to go here https://dashboard.ionicjs.com/login . Login in after that navigate to push from the dashboard and send the push notification.

Or if you want use API references to send push notification,then you can use this API endpoint to create push notifications.

Once you receive a background notification, you must handle it properly. On iOS, you have 30 seconds to handle a background notification or the OS will kill your app. You must use the push.finish() handler after you’re done processing the notification.

push.on('notification', function(data) {
// do something with the push data
// then call finish to let the OS know we are done
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);
});

Hope you enjoyed the code…

Happy coding!

· · · ·

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.

Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.

How to implement navigation drawer in flutter

The navigation drawer concept actually comes from the android native applications. In android, we use fragments and drawer files for managing navigation but it is bit different in flutter to create drawer and page routes, this article will help you create the same in a flutter application.

Read More

Getting started with Ranorex

Ranorex is a powerful tool for the automation of testing It is a GUI test automation platform that is used to test cloud, desktop, and mobile applications.

Read More

Updates in Angular 9

Angular is one of the leading open-source frameworks for web and mobile application development. Throughout the years, Angular has developed into a robust development platform that includes all the resources and components needed to build a web app.

Read More