Set Up Your Mobile App for push notification:
In our mobile app development company ,To get started with FCM, you’ll have to create a new Firebase project in the Firebase Developers Console. You can do this by either starting a new fresh project, or importing an existing Google project.
Follow these steps to set up your project for Android. By the end of it, you should have an FCM server key and a google-services.json configuration file. Place the configuration file in the app/ directory of your Android project.
To upload your FCM server key to pusher, visit the Pusher dashboard. You can sign up for a free account if you do not have one already. Create an app and under the Push Notifications tab, head to Configure FCM. Enter your FCM server key and click Save.
Now your app should be provisioned to send and receive FCM notifications.
 
Set up for ANDROID Mobile app:
 
To send push notifications to Android devices, you must use the Google Cloud Messaging (GCM).
Use valid Gmail account to register to the GCM service.
Note: Google recently announced a move from GCM to FCM. The below instructions have been updated accordingly. Also note that                existing in-the-field GCM configurations will continue to function however new GCM configurations will not, and FCM must be used          instead.                                                                                                                                                                                 
Android devices use the Firebase Cloud Messaging (FCM) service for push notifications. To setup FCM:
    1.Visit the Firebase Console.
    2.Create a new project and provide a project name.
    3.Click on the Settings “cog wheel” icon and select Project settings.
    4.Click the Cloud Messaging tab to generate a Server API Key and a Sender ID and click Save.
 
Set up for IOS Mobile app:
 
To send push notifications to iOS devices, you must use the Apple Push Notifications Service (APNS).
As a developer, you must be a registered Apple iOS Developer to obtain an APNS certificate for your application.
Note: APNS certificates must have a non-blank password.
  • In the development phase, the sandbox certificate file should be apns-certificate-sandbox.p12 and be placed in the environment root folder or in the application root folder. The environment root folder takes the highest priority.
  • In production, the production certificate file should be apns-certificate-production.p12 and be placed in the environment root folder or in the application root folder. The environment root folder takes the highest priority.
When the hybrid application has both iPhone and iPad environments, it requires separate certificates for each environment. In that case, place those certificates in the corresponding environment folders.

Steps for Integrating Firebase and FCM SDK

  1. Add Firebase to your app

Go to Firebase console and either create a new project or import an existing one. After creating or importing your project, a welcome screen will open; like below.

Android,IiOS hybrid App,Mobile App Development

As I’m into Android, I’ll be adding Firebase to my Android app. However, steps for Android, iOS and Web app are almost same.

Click on Add Firebase to your app.

Android,iOS hybrid mobile app,Mobile app Development

Add package name by copying it from AndroidManifest.xml file and get SHA-1 key by using below command :

$ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

It may ask for keystore password: Type “android” if using debug.keystore. After entering required information click on Add App. Now it’ll ask you to save downloaded google-services.json file. Save it in the root of app folderof your app. Next, you’ll be asked to add the following dependencies to your gradle file for accessing Firebase SDKs.

Hybrid Mobile app android iOS, Mobile App development

Instead of adding complete client SDK, you should add dependencies for the Firebase SDKs you wish to use. Like in our case, its

compile ‘com.google.firebase:firebase-messaging:9.2.1′

Sync your project.
If you are getting a build error complaining about duplicate files you can choose to exclude those files by adding the packagingOptions directive to your build.gradle file, inside the android domain:

packagingOptions{
exclude ‘META-INF/LICENSE’
exclude ‘META-INF/LICENSE-FIREBASE.txt’
exclude ‘META-INF/NOTICE’
exclude ‘LICENSE.txt’
}

Click on finish and you are done. Firebase is added to your app now.

Now let us first understand how Firebase works ?

Client app registration process – 

fire base, android iOS hybrid mobile app

Send notifications using FCM

Hybrid Mobile App Development,ios android

Since, you have understood by now how FCM works, lets begin some coding.

  1. Add internet permission to your manifest file.                                                                                                                <uses-permission android:name=“android.permission.INTERNET” />
  2. Now we need to add a service that extends FirebaseMessagingService. This is the Base class for communicating with Firebase Messaging. This FirebaseMessagingService extends Service class. Class hierarchy followed is :

This class provides various functionalities :

  • automatically displaying notifications.
  • message handling beyond receiving notifications on apps in the background.
  • receive notifications in foregrounded apps
  • receiving data payload
  • sending upstream messages
  • receiving errors in case of upstream message failures.

       To handle any type of events required by the application, we need to override this base class methods. These methods are invoked on a background thread. To add this service include following to your manifest file :

    3. Now we need to add a service that extends FirebaseInstanceIdService. This is the Base class to handle Firebase Instance ID token refresh events. This FirebaseInstanceIdService extends Service class.

Class hierarchy followed is :

1 java.lang.Object
2 ↳android.content.Context
3 ↳android.content.ContextWrapper
4 ↳android.app.Service

It provides various functionalities :

  • Creation of registration tokens
  • Rotation of registration tokens
  • Update process of registration tokens
  • Sending notification to a single device or group of devices
  • Allows devices to subscribe to various topics with the server subscription management API.

If your app requires Instance ID or uses Instance ID tokens, then we can extend this class and implementonTokenRefresh() to receive token refresh events. To add this service include following to your manifest file :

Now create the respective service classes in your Android code.

Retrieving & monitoring of device registration token

On initial startup of our app, the FCM SDK will generate a registration token for the client app instance. If we want to target a single device or create device groups, we’ll need this token which can be retrieved from our MyFirebaseInstanceIDService class. This token could be rotated or changed after initial startup. So, I would strongly recommended you to fetch the latest updated registration token using   FirebaseInstanceId.getInstance().getToken() ;   unless you specifically need to retrieve the current token. So to retrieve the token, simply override onTokenRefresh() as  below:

If the system determines that the token needs to be refreshed, then this callback is called. Once the token is retrieved, you can save it to your server and store it using your required method. This will not be called very frequently. It is needed for key rotation and to handle Instance ID changes; which happens in following cases:

  • When app deletes Instance ID
  • When app is restored on a new device
  • When user re-installs or uninstalls the app
  • When user deletes the app data

If you have specific need to retrieve current token call call FirebaseInstanceID.getToken(). It returns null if the token has not yet been generated.

Once this is set up we are ready to start sending downstream messages with the Firebase console .(Downstream messages means sending messages from your app server to Firebase Cloud Messaging client apps). However, lets skip that part for now. Let us first understand how to handle received messages on client side, otherwise some users may not receive the notifications we send. This includes any users who have your app in the foreground on the device.

Receiving and handling messages

In order to receive messages, we have to override the onMessageReceived() callback from our FireBaseMessagingService class; keeping in mind the exceptions mentioned below :

  • Notifications delivered when your app is in the background – In this case, notification is delivered to the system tray of the device. A user’s tap on a notification opens the app launcher by default.
  • Messages with notification + data payload – In this case, the notification is delivered to the device’s system tray, and data payload is delivered in the extras of the intent of your launcher Activity.

This is also called if any notification message is received while user is interacting with the app i.e. app is in the foreground. To fetch notification parameters use getNotification() method.If we need to perform some action based on the message received and access message data, we will have to override this method.

How to send a message from the FireBase console?

  1. Install and run the app on the target devices.
  2. Open the Notifications tab of the Firebase console and select New Message.
  3. Enter message text.
  4. Select the message target (devices). The dialog displays further advanced options to filter the target devices by allowing you to choose from App Version, Users in Audience or Device Language.

FireBase console to send messages

Once you click Send Message button, client devices you targeted, that have the app in the background, will receive notification in the system notifications tray. Whenever the user will tap on the notification, the app launcher will open up your app. If you want to send a message to a particular device: select “Single Device” from options available and insert the token you received.

Various other advanced options are available which you can explore yourself by playing around with them like :

  • the expiration period
  • play a sound when the notification is received
  • Setting custom data with some message
  • setting the notification priority – normal or high

Normal priority – This is the default priority for message delivery. These messages do not open up network connections if your device in is “Doze mode”, and their delivery is delayed to preserve the battery.

High priority – FCM delivers high priority messages immediately, permitting the FCM service to wake a device which is in “doze mode” when possible and open a network connection to your app server. Apps which have features like instant messaging, chat, or voice call alerts, generally need to open a network connection to make sure that FCM delivers the message to the device without any delay. Set messages to high priority only when your message is time-critical and it requires immediate response from the user. However, keep in ind that setting your messages to high priority contributes more to battery consumption compared with normal priority messages.

Author: Ramanji

Web developer at colors software