In this article, we are going to learn how to integrate Firebase Cloud Messaging in Android applications.
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost.
Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention.
For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app.
FCM relies on the following set of components that build, transport, and receive messages.
Let’s create one project and start integrating FCM.
Before doing anything go to the firebase console and create the project by using the following steps:
1. Open the firebase console and login with your Gmail account or create a new account.
2. Now click on the + Add Project button to create a new project.
3. After that enter your project name and click on the continue button.
4. Then again click on the continue button.
5. After that select your Google Analytics Account to which you want to connect and click on the create project button.
6. It will take some time to create the project and once your project is created then click on the continue button again and it will take you to the project dashboard/console.
Firebase can be setup in two ways:
Android Studio
1. Open Android Studio and navigate to Tools -> Firebase.
2. It will open Firebase Assistant containing all list of services provided by Firebase.
3. Find Cloud Messaging and click on it. After clicking on it it will ask you to do 3-4 steps.
4. Firstly, click on connect to Firebase button to connect your project with the firebase project which we created.
5. Once both projects are connected, then come back to Android Studio and it will show connected instead of the connect to firebase button.
By doing this it will add google-services.json file into your app directory.
6. Secondly click on Add FCM to your app button to add the dependencies to your project. It will open a window to accept the changes.
7. After then sync your project and your project is connected with Firebase successfully.
Firebase Console
1. Go to the firebase console and click on the Android icon to connect your project.
2. Then add your android package name and click on the Register App button.
3. Then it will ask you to download the google-servies.json file. Download the file and put it inside your app directory.
4. After that click on the Next button and it will ask you to add the dependencies to your project. Add the same dependencies which were added automatically previously.
5. Once the dependencies are added and your project is synced means your project is connected with Firebase successfully.
Firebase cloud messaging works on the token. So we will see how we can generate tokens on the client-side.
1. Create a new java class with the name MyFirebaseMessagingService.java and extend it with the FirebaseMessagingService and override the onNewToken() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.androhub.fcmdemo; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import java.util.Map; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); @Override public void onNewToken(@NonNull String token) { super.onNewToken(token); Log.d(TAG, "Token: " + token); //upload the token to your server //you have to store in preferences } } |
2. After that declare your Service in AndroidManifest.xml like below:
1 2 3 4 5 6 |
<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> |
Here the action com.google.firebase.INSTANCE_ID_EVENT is responsible to listen to token changes in the device.
3. Inside the onNewToken() method we will be getting the token when the user installs the app the first time. Here we can upload the token to the server and we can store it in preferences for later use.
4. When we will run the app we can see the token in the logs.
There are few scenarios when onNewToken() is called:
=> When a new token is generated on the initial app startup.
=> App is restored to a new device or reset the device.
=> User uninstalls/reinstalls the app.
=> User clears app data.
5. Let’s suppose we have to retrieve the token manually. To do that we have to use the below code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Log.e(TAG, "Failed to get the token."); return; } String token = task.getResult(); Log.d(TAG, "Token : " + token); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e(TAG, "Failed to get the token : " + e.getLocalizedMessage()); } }); |
The task will be asynchronous so we have to wait till we receive the token.
Note: To generate the token internet connection is required. If there is no internet connection then no token will be generated.
Thanks.
Subscribe to us and get the latest news.