firebase push notification android studio tutorial

Firebase Cloud Messaging Push Notifications Android tutorial

In this tutorial I will explain how you can integrate Firebase Push Notification SDK in your Android Application and how to send push notification from Firebase console and from Application Server to your Android Application.

Create project in firebase console FireBase console Link . Your project ID while creating project will be applicationId in build.gradle.

Download google-service.json file and place it in app folder of your Android project.

Now setup Firebase SDK in Android project.

Updated 30 Oct 2018

Add this dependency in module build.gradle file

implementation ''

Add this at bottom of module build.gradle file.

apply plugin: ‘’

Add this in project build.gradle file

classpath ‘’

Kotlin Code Example:

If you are still using Java please go down and find Java Code.

Create a new package ‘firebase’ in your project.

We will create a new Firebase Messaging Class in this package.

First of all declare Messaging Service class in Manifest file.

<service android:name=".firebase.MyFirebaseMessagingService">
<action android:name="" />

Create a new class and name it MyFirebaseMessagingService

This classs is responsible for generating new firebase refresh token.

You will get token callback inside onNewToken function.

  • I have also added code for parsing notification and displaying local notification if it is received inside onMessageReceived class.


// MyFirebaseMessagingService.kt

class MyFirebaseMessagingService : FirebaseMessagingService() {

override fun onNewToken(p0: String?) {
mSharedPreference!![SharedPrefFlag.fcmToken] = p0

override fun onMessageReceived(remoteMessage: RemoteMessage?) {

Log.d(MewConstants.mewLogs, "notification received: " + remoteMessage)


var notificationData = remoteMessage?.data

val title =notificationData?.get("title")
val message =notificationData?.get("message")

// Create an explicit intent for an Activity in your app
val intent = Intent(this, {
putExtra("isFromFCMNotification", true)

val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val mBuilder = NotificationCompat.Builder(this, "default")
// Set the intent that will fire when the user taps the notification

with(NotificationManagerCompat.from(this)) {
// notificationId is a unique int for each notification that you must define

private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
val importance = NotificationManager.IMPORTANCE_HIGH

val channel = NotificationChannel("default", name, importance).apply {
description = descriptionText
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
Old Firebase version and Java Code Implementation:

Declare the service classes in manifest file. we will just create two classes. MyFirebaseInstanceIDService classs will extend FirebaseInstanceIdService which will be responsible for handling Firebase token. Here you will get token which will be used to send notification to a single device.

And second service class MyFirebaseMessagingService will extend FirebaseMessagingService.

Here you will receive and handle Firebase Push Notifications.

 <action android:name=”” />
<service android:name=”.MyFirebaseInstanceIDService”>
 <action android:name=”” />

4. Add above declared service classes.

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
 public MyFirebaseInstanceIDService() {
 public void onTokenRefresh() {
 // Get updated InstanceID token.
 String refreshedToken = FirebaseInstanceId.getInstance().getToken();
 Log.d(“firebase”, “Refreshed token: “ + refreshedToken);

// We will Send this refreshedToken to our app server, so app
 // server can save it
 // and can later use it for sending notification to app.

// sendRegistrationToServer(refreshedToken);

public class MyFirebaseMessagingService extends FirebaseMessagingService {
 public MyFirebaseMessagingService() {
 public void onMessageReceived(RemoteMessage remoteMessage) {

Log.d(“firebase”, “From: “ + remoteMessage.getFrom());
 Log.d(“firebase”, “Notification Message Body: “ +


Till now we have used official source code from Firebase which you may have seen at Firebase website or already added. Next is the actual thing.

Now we are done with adding Firebase in Android Application.

Now you can login to Firebase console and can send push notification

If you want to send push notification from your app server.

Go to Firebase project → Project Settings → Cloud Messaging and copy your firebase project key. we will use this project key for sending push notification from app server or from rest client.

I will use Rest Client for demo purpose.


HEADER: Authorization:key=AIzaSyD_Vw3Zf8XXXSDMSDKLMGyqR_Kyw5o

PARAMS: Mentioned in image below.

rest client example push notification
sending firebase push notification from rest client

If you are getting internal server error(500) or unauthorized(401) than your server key is incorrect.

See I sent push notification to my device using rest client. Now you can develop your REST API accordingly for this purpose.

Note: I have not added sending Firebase token to your app server.

Something more about Sending Notification from Firebase.

    1. If you are sending notification from firebase console and your app is in background onMessageReceived method will not be called inside MessagingService class which we added above.
    1. Firebase will handle it at Backend.
    1. It will send this Notification to system for displaying Notification in Notification tray.
    1. And there will be no Notification sound even if you have enabled/allowed Notification sound for
  1. Also Firebase SDK will use default Application launcher icon from manifest file for Notification.

If you don’t want to use default Application icon for Notification and default Notification sound you can customize Notification icon and Notification sound using below code


“to” : “bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1…”,

“notification” : {

“body” : “great match!”,

“title” : “Portugal vs. Denmark”,

“icon” : “myicon”,

“sound” : “mySound”



icon should be in your app drawable folder. and mysound file should be in raw folder.

We have customized notification icon and notification sound. but still firebase is managing it at backend. onMessageReceived method is not called and we have not processed notification.

If you want onMessageReceived to be called when notification is received from firebase. Than there is another thing which you need to understand.

From official Firebase docs


 For downstream messaging, FCM provides two types of payload: notification payload and data payload.

For notification type FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.


For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs (JSON Object) .

So if you want to receive and process push notification in your Android app You need to send data payload.

This is how to send data payload for push notification.

{ “data”: {
 “title”: “Firebase notification”,
 “detail”: “I am firebase notification. you can customise me. enjoy”,
 “to” : “efaOvIXDbik:APA91bEkNUVWNaoA….”

Now Firebase server will not send push notification to OS for handling and displaying push notification in notification tray.

It will leave it for client/developer to receive and handle notification.

Overridden method onMessageReceived will be called and developer can handle it.

This blog post can answer following questions.

  • How to send Firebase push notification from rest client ?
  • How to customize Application notification icon  / How to change default notification icon?

If you want to send push notification to a single user from app server you need Firebase token of that user.

Firebase SDK is responsible to generate that token. You can save token to your app server.

If you want to send Firebase push notification from your app server to all users. you can send notification to topics.

Users can subscribe to topics.

Recommended Reading :-

Link for more details on How to send push notification from app server.

Hello! I am Hammad Tariq. Jack of All trades and Yet master of Many! Senior Android Application Developer | Cross-platform Development | Flutter | Backend Development (Spring Boot + Kotlin + MySQL) | Blogger | Founder I am an all-around Mobile Developer who is passionate about learning the latest technologies and trends. I graduated from Air University Islamabad, Pakistan in 2015 but started working on Android Development, Universal Windows Apps development long before that. Currently, I am working as a team lead and Senior Android Developer at EVAMP SAANGA, Pakistan.
Posts created 43

11 thoughts on “Firebase Cloud Messaging Push Notifications Android tutorial

    1. May be you have missed anything 🙂
      Check Logcat if firebase token was generated, and if your device is connected to internet and all that.. it should work 🙂

  1. Hello.. in the app i can configurate the vibration and sound.. but in the app server i cannot? .. 🙁

    How can I configure that?
    my code jquery request is this:
    url : “”,
    headers : {
    Authorization : ‘key=’ + ‘Axxxxxxxxxxxxxxxxxxxxxxxxxx’
    contentType : ‘application/json’,
    dataType: ‘json’,
    data: JSON.stringify({
    “to”: “/topics/se”,
    “notification” : {
    “body” : “great match!”,
    “title” : “Portugal vs. Denmark”
    success : function(response) {
    error : function(xhr, status, error) {

    1. sound can be configured using sound key in API request and that sound file should be res/raw folder.
      I have not looked into vibration, let me check and will update you if i find anything helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top

Contact Us