- 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.
Steps for Integrating Firebase and FCM SDK
- 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.
Click on Add Firebase to your app.
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.
Instead of adding complete client SDK, you should add dependencies for the Firebase SDKs you wish to use. Like in our case, its
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:
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 –
Send notifications using FCM
Since, you have understood by now how FCM works, lets begin some coding.
- Add internet permission to your manifest file. <uses-permission android:name=“android.permission.INTERNET” />
- 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 :
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?
- Install and run the app on the target devices.
- Open the Notifications tab of the Firebase console and select New Message.
- Enter message text.
- 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.
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.
Web developer at colors software