Hello, in this tutorial, I will show you how to send and display notifications in Android using Firebase Cloud Messaging.
Hello, in this tutorial, I will show you how to send and display notifications in Android using Firebase Cloud Messaging.
Setup
Before we begin, you’ll need to have a Google account. If you do not have one, go to accounts.google.com/signup to sign up for one.
accounts.google.com/signup
You’ll also need to have a Firebase project. To create one, go to console.firebase.google.com, sign in with your Google account, and create a project.
console.firebase.google.com
Once you have your Firebase Project, click on the Android icon in the Project Overview page and add Firebase to your Android application.
For the package name, use the package name from your Main Activity file for your Android project.
Copy the SHA-1 Certificate in the terminal and paste it inside the textbox in Firebase.
Go to the Firebase console and continue to step 3.
Copy the code in the dependencies section and add it to the dependencies section of your project’s build gradle file.
Go back to the Firebase console and scroll down.
Copy the apply plugin code and add it to your project’s app gradle file in Android Studio.
apply plugin: 'com.google.gms.google-services'
Continue by copying the dependencies code and add them to your app.
Click on “Sync Now” and wait until the process is finished.
In the Firebase console, continue to the next step to complete the process.
Handling Notifications
Create a new class call PushNotificationService and have it extend the FirebaseMessagingService class.
Go to the manifest file and add the service to the app.
This is all we need to do to start receiving notifications from Firebase.
Sending Notifications using Firebase Cloud Messaging UI
Let’s see how we can send a notification.
We can use this tool to send out notifications to a specific group, device, or topic.
If we go to the emulator, a notification should appear in the status bar.
Modifying the Notification Behavior
Displaying the Notification
There are 4 importance levels: IMPORTANCE_HIGH, IMPORTANCE_DEAFULT, IMPORTANCE_LOW, and IMPORTANCE_MIN.
getSystemService(NotificationManager.class)
Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID)
Call setContentTitle() to set the title.
Notification.Builder notification =
NotificationManagerCompat.from(this).notify(1, notification.build());
Full Code
If we run the app and send a notification from the Firebase console, a Heads-Up notification will be displayed.