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.

Add this dependency in module build.gradle file

compile 'com.google.firebase:firebase-messaging:11.8.0'

Add this at bottom of module build.gradle file.

apply plugin: ‘com.google.gms.google-services’

Add this in project build.gradle file

classpath ‘com.google.gms:google-services:3.1.1’

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.

<service
 android:name=”.MyFirebaseMessagingService”
 android:enabled=”true”
 android:exported=”true”>
 <intent-filter>
 <action android:name=”com.google.firebase.MESSAGING_EVENT” />
 </intent-filter>
 </service>
<service android:name=”.MyFirebaseInstanceIDService”>
 <intent-filter>
 <action android:name=”com.google.firebase.INSTANCE_ID_EVENT” />
 </intent-filter>
 </service>

4. Add above declared service classes.

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
 public MyFirebaseInstanceIDService() {
 }
 @Override
 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);
 }
 }
And

public class MyFirebaseMessagingService extends FirebaseMessagingService {
 public MyFirebaseMessagingService() {
 }
 @Override
 public void onMessageReceived(RemoteMessage remoteMessage) {
 super.onMessageReceived(remoteMessage);

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

}
}

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.

How To Send Firebase Push Notification From App Server Tutorial

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.

URL : https://fcm.googleapis.com/fcm/send

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.
  2. Firebase will handle it at Backend.
  3. It will send this Notification to system for displaying Notification in Notification tray.
  4. And there will be no Notification sound even if you have enabled/allowed Notification sound for
  5. 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.

Posts created 26

8 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 : “https://fcm.googleapis.com/fcm/send”,
    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) {
    console.log(response);
    },
    error : function(xhr, status, error) {
    console.log(xhr.error);
    }
    });
    $(“#alert”).show().fadeOut(3000);
    });

    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