Android Tutorials : Firebase Push Notification Tutorial

AndroidBash Firebase Push Notification

Firebase cloud messaging (FCM) is a new version of Google Cloud Messaging (GCM). Using FCM you can send notification messages to your client application in order to drive user engagement. With FCM, you can send two types of messages to the client app: Notification messages and Data messages, A notification message is the more lightweight option, with a 2KB limit and a predefined set of user-visible keys. Data messages let developers send up to 4KB of custom key-value pairs. Notification messages can contain an optional data payload, which is delivered when users tap on the notification. Use notification messages when you want Firebase cloud messaging (FCM) to handle displaying a notification on your client app’s behalf. Use data messages when you want to process the messages on your client app.

Firebase Cloud Messaging

Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded (still running) apps to receive notification messages or data messages, you’ll need to write code to handle the onMessageReceived callback. In the overridden method FirebaseMessagingService.onMessageReceived(…), you can get the message data from the received message and perform the desired action according to the needs of your android app.

So to receive messages, you should use a service that extends FirebaseMessagingService. Your service should override the onMessageReceived callback. The method onMessageReceived(…) will not get called if the app is in background or killed state, when the message is sent through Firebase Console. But when the message is sent via API (perform a POST to the following URL : https://fcm.googleapis.com/fcm/send ), the method onMessageReceived(…) will get invoked. So in this tutorial we will be sending messages via Firebase console as well as via API.

Project on Github

Now let us create an Android application to which we can send push notifications using Firebase Notifications. The steps will be described in five detailed yet simple parts.

Part ! : Includes steps to create a new Android application and set up Firebase in it.

1. Create a new Android Project in Android Studio. Give it a name and select the Minimum SDK on which your app will run on. I chose API 16 : Android 4.1 (JELLY_BEAN).

2. When you are prompted to add an activity to your application choose Blank Activity and click on next button.

3. In the next step click on Finish and in few seconds your application should be loaded in Android Studio.

4. Open build.gradle(Module:App) file of your application and add the following dependencies inside dependencies section of build.gradle (Module:App) file.

5. Now add the packagingOptions directive to your build.gradle(Module : App) file as shown below. This is how your build.gradle (Module : App) will look now.

6. The application requires following permissions to work. Your app might not work unless you add these permissions to your AndroidManifest.xml file.

Part !! : Includes Firebase account creation and getting google-services.json file from Firebase console

1. The first thing you need to do to get started with Firebase is sign up for a free account. You can use your Google account to sign in to your firebase account.

Android Firebase AuthUpdated

2. After clicking on ‘Sign In with Google’ you will be asked to allow the Firebase to view your Email and your basic profile. Click on Allow button to continue.

Firebase Email Authentication

3. Once you are signed in, Click on Go to your Console button if you are not automatically redirected to your firebase console. Click on Create New Project button in your firebase console.

Android Firebase AuthUpdatedAndroidBash Firebase Push Notification

4. Now you can see an overview of your new Firebase project. Now click on Add Firebase to your Android App as shown below.

AndroidBash Firebase Push Notification

5. Now you need to enter your App details (your application’s package name) and also get SHA-1 finger print and paste it in the field as shown below.

AndroidBash Firebase Push Notification

Click on Add App button. Upon clicking it, a file named google-services.json gets downloaded to your machine.

Note : Following image shows how to get SHA-1 from Android Studio.

AndroidBash Firebase SHA-1

6. Copy the google-services.json file and paste in the app folder of your Android application.

AndroidBash Firebase

Note: If you forget to copy and paste google-services.json file you will get the following error when you build your app.

Android Firebase AuthUpdated

7. Open the build.gradle (project level) file of your android application and add classpath ‘com.google.gms:google-services:3.0.0’ in the dependencies section. Your build.gradle (project level) file will look as shown below.

8. Now add apply plugin: ‘com.google.gms.google-services’ at the bottom of your build.gradle (App level) file, just below dependencies section. Also check whether you have added the following dependencies in the dependencies section of build.gradle (App level). Click on sync now or re-build the android application.

AndroidFirebaseAuthUpdated

9. The following section in the Firebase console shows the overview of your project. Click on Notifications button in the left menu to go to Notifications tab of your Firebase console. Before you send your first notification, let us code our android app to handle Firebase Notifications.

AndroidBash Firebase Push Notification

Part !!! : Includes modifications to build.gradle file and other XML files

1. At this point of time, the build.gradle (Module:app) file should look like below.

2. And also, the build.gradle (Module:project) file should look like below.

2. In order to use Firebase notification, open your AndroidManifest.xml and add the following under application tag.

3. Create colors.xml file in the values folder and add the following code. You can change the colors to change the look of the application.

4. The menu_main.xml file in the menu folder looks like this. Menu includes a sign out button in it.

5. The styles.xml file in the values folder looks like this.

6. The strings.xml file in the values folder looks like this. Always keep a habit of including all your xml string resources in this file.

Part !V : Includes creation of new XML layout files and modification to activity_main.xml file

1. Create a new XML layout resource file and name it as activity_another.xml. It includes an Imageview and a Textview in it. The activity_another.xml file of our application has the following code in it.

2. The acivity_main.xml includes an ImageView and TextView. The acivity_main.xml has the following code in it.

Part V : Includes creation of new Java classes and modification to MainActivity.java file

1. Create a new java class in your package and name it as AnotherActivity.java. This is a simple Activity class which gets opened when the user taps on a notification message which includes a key named as “AnotherActivity”.

2. Now create another new java class and name it as MyFirebaseInstanceIDService.java. It extends FirebaseInstanceIdService class and contains an overridden method onTokenRefresh(). This method is called if InstanceID token is updated. This may occur if the security of the previous token had been compromised. Note that this is called when the InstanceID token is initially generated so this is where you would retrieve the token. This class has the following code in it.

3. Now create another java class and name it as MyFirebaseMessagingService.java. It extends FirebaseMessagingService. It contains an overridden method onMessageReceived(RemoteMessage remoteMessage). If you want foregrounded (still running) apps to receive notification messages or data messages, you’ll need to write code to handle the onMessageReceived callback. The method onMessageReceived(…) will not get called if the app is in background or killed state, when the message is sent through Firebase Console. But when the message is sent via API (perform a POST to the following URL:https://fcm.googleapis.com/fcm/send ), the method onMessageReceived(…) will get invoked. We will be showing both the ways to send notification. This class has the following code in it. Please go through the comments written in the code.

4. Open MainActivity.java and add the following code in it. It has a method named subscribeToPushService(). This method is invoked every time the user opens your app. This is where the user subscribes to notifications. MainActivity is the default activity which gets opened when the user taps on the received notification. But once the MainActivity is loaded we check for a key named “AnotherActivity” in the intent data that is passed to it. If the value of the key equals “True” then we are redirecting the application to AnotherActivity.java.

5. Finally here is how your AndroidManifest.xml should look.

That’s it. Run the application to subscribe to Firebase push notifications. Now you can start sending notifications to all the subscribed users.

Here is how you send Push notifications along with image.

We will be showing 2 ways to send notifications.

1. Using Firebase console : Go to the overview section of your Firebase console and click on Notifications button on the left menu. Notification tab gets opened as shown below. Click on Send your First Message button. Enter the details of your push message in the fields provided.

AndroidBash Firebase Push Notify

We have included three key-values pairs [(image->https://ibin.co/2t1lLdpfS06F.png) & (AnotherActivity->True) & (message-> “AndroidBash First Push message”)] in the message as shown in the image below.

AndroidBash Firebase Push Notify

Verify the details and click on send button.

AndroidBash Firebase Push Notify

When sent using Firebase console, if the app is in the foreground then onMessageReceived() method will be called. Hence a notification with image an fetched from the url is displayed to the user (As shown in the Result 1 ). But if the app is background or killed state then onMessageReceived() method will not be called. Hence a simple notification containing just a message will be displayed in the notification bar of your android device. (As shown in the Result 2).

Result 1

PushNotify Result 1

Result 2

PushNotify Result 2

2. Using Messaging API : To send a message using API, you can use a tool called AdvancedREST Client, its a chrome extension, and send a message with the following parameters.

Authorization key can be obtained by visiting Google developers console and click on Credentials button on the left menu for your project. Among the API keys listed, the server key will be your authorization key.

And you need to put tokenID of the receiver in the “to” section of your POST request sent using API. You can get the tokenID when you run your android app. We log the tokenID in the subscribeToPushService() method of the MainActivity.

AndroidBash Firebase Push Notify

When the notification is sent using API, onMessageReceived() method will be called whether or not the application is in foreground. The following image shows the result of the notification sent using API.

AndroidBash PushNotify Result 3

You can download the project and add your google-services.json file (downloaded from Firebase console of your Firebase App) under app folder and try it out.

Download Project

Project on Github

If you have liked our tutorial, you can help us keep this website free for all Android enthusiasts by donating any small amount on my PayPal account. If you have followed our tutorial please do let us know by commenting below. It makes us write more and more articles on android application development. In case if you get stuck somewhere please do comment below and let us know. We usually reply within a day.

Note : Do not forget to :

Add google-services.json file under “app” folder.

Update Google Play Services and Google Repository to the latest versions available.

Get SHA-1 finger print and paste it during the creation of your firebase project.

Add all the required dependencies in the build.gradle file of your application.

Firebase Push Notification With Image Tutorial on Android : Firebase Cloud Messaging

34 thoughts on “Firebase Push Notification With Image Tutorial on Android : Firebase Cloud Messaging

  • September 7, 2016 at 12:39 pm
    Permalink

    hiii…i want to image without another activity key how i get image in notification.?
    and i want to give some parameter like bday date and how i acess mysql database in console..?

    Reply
    • September 12, 2016 at 2:08 pm
      Permalink

      Hello Jaydip, You can send any number of key-value pairs from Firebase console or using messaging API. You can retrieve the values in onMessageReceived(RemoteMessage remoteMessage) method of MyFirebaseMessagingService class.

      Reply
  • September 8, 2016 at 12:04 pm
    Permalink

    Thanks alot.. It was clear explanation with comments… keep it up..

    Reply
  • September 26, 2016 at 6:45 am
    Permalink

    I have a problem. I get notification with icon while app is in foreground but when app is in background the notification is received but the icon and notification sound is missing. I think onMessageReceived() is not called when the application is in background. I tried many solution found on the web but still the problem persists.

    Reply
    • September 27, 2016 at 10:51 am
      Permalink

      Yes Dadhi. onMessageReceived() is not called when the app is in background if you are using Firebase console to send a Push message. So you need to send Push message from “Messaging-API” as explained in the tutorial. If you send the Push notification from “Messaging-API” then onMessageReceived() will be called. Make sure you set the notification sound inside onMessageReceived().

      Reply
    • October 14, 2016 at 6:41 am
      Permalink

      I’m facing the same issue. When the app is in background, the image doesn’t appear in the notification drawer

      Reply
      • October 14, 2016 at 2:30 pm
        Permalink

        Hello Shraddha , Did you use Firebase console to send push message? Or Messaging API?

        Reply
        • November 22, 2016 at 10:29 pm
          Permalink

          I am using the Messaging API and have everything working:
          (1) Push notification received with title and text
          (2) Onclick, open app, launch activity and display image in imagview from ‘image’ key in the received push notification

          The thumbnail is not working from the Messaging API. I’ve tried small images (e.g. 10kb), but no luck. Any help would be appreciated! The below is

          var body = {
          to: ‘/topics/test’,
          priority: ‘high’,
          notification: {
          title: ‘test’,
          text: ‘testing’,
          image: ‘http://avatarbox.net/avatars/img32/test_card_avatar_picture_88303.jpg’
          },
          data: {
          title: ‘test’,
          text: ‘testing’,
          image: ‘http://avatarbox.net/avatars/img32/test_card_avatar_picture_88303.jpg’
          }
          };
          var bodyStringified = JSON.stringify(body);

          // Set up the request
          var post_req = http.request(options, function(res) {
          res.setEncoding(‘utf8’);
          res.on(‘data’, function (chunk) {
          console.log(‘Response: ‘ + chunk);
          });
          });

          Reply
  • October 9, 2016 at 4:05 pm
    Permalink

    Sir I tried this using your tutorial in my app , everything goes right , but iam facing one issue, that is when I launch my app for the 1st time , it is force closing leaving a msg ” Unfortunately App has been stopped” , and from second launch its working fine. please help me in fixing this.

    Reply
    • October 10, 2016 at 8:01 am
      Permalink

      Hello Rohith, Can you please post your logcat message? When an exception is thrown it will be logged in the logcat as an Error message. You can paste your logcat message on http://pastebin.com and give me a pastebin link to your file.

      Reply
    • November 21, 2016 at 10:55 am
      Permalink

      I think your token has not been ready for the very first time.

      Reply
  • November 8, 2016 at 6:57 pm
    Permalink

    Very Well Explained. Only 1 problem Through API i am able to send image push notification to a single user. Is there anyway to send image push notification to all app users

    Reply
  • November 15, 2016 at 8:09 am
    Permalink

    Thanks,
    I solved my problem by referring your tutorial.
    Really nice work,
    keep it up.
    waiting for more

    Reply
  • November 17, 2016 at 10:19 am
    Permalink

    onMessageReceived() not called when app in Background and i have tried “Messaging-API”, it give 200 status code but i did not get notification also? how can i get image in notification when app in background?

    Reply
    • November 18, 2016 at 8:31 am
      Permalink

      sir now onMessageReceived() called when app is background but when i use our database(Console) then app in background , onMessageReceived() not called from console, which code require in server side? when i use “Messaging-API” , onMessageReceived() called but from console it doesn’t work.

      Reply
  • December 1, 2016 at 10:01 am
    Permalink

    Everything is working perfectly, but I am not getting any image in the notification. I sending notification using api plugin u have mentioned.

    Reply
    • December 2, 2016 at 1:08 pm
      Permalink

      It should work actually. Can you please try again and also please cross check the image link again.

      Reply
  • December 6, 2016 at 10:50 am
    Permalink

    Thanks for a step to step explanation. 🙂

    Reply
  • December 8, 2016 at 10:01 am
    Permalink

    Nice tutorial! I just want to ask if it is possible for Firebase push notifications be trigged in my Android app? Here’s a scenario. I have an app that has registration and log in for users. I want to send a notification when the user is already registered in the app, then a simple notification will appear that says “Welcome! You are now registered.” Is this possible on Android Firebase? Thanks for your help.

    Reply
    • December 8, 2016 at 5:25 pm
      Permalink

      If you want to display just this text whenever a user completes registration then it can be done by creating a notification. Please refer this link to create a simple notification. You need not use Firebase notification for this i guess. Thank you.

      Reply
  • December 12, 2016 at 4:31 am
    Permalink

    I need only data payload from firebase not a notification ,is it possible ???
    Bcz when I send from firebase along with key n value pair …I got two notification …first from firebase notification n otherone is my app responsible to data payload to open image notification..so I need only data payload from firebase

    Reply
  • December 14, 2016 at 6:54 am
    Permalink

    Hello,
    I followed every single (except adding SHA-1 to google-service.json) step, but i can not receive messages that was sent from the firebase console.

    Reply
    • December 16, 2016 at 2:58 pm
      Permalink

      Hello Ahmet, Can you please tell me the error that is being displayed in log? Also please follow all the steps in the tutorial. Please try to add SHA1 and re-download google-services.json. Thank You!

      Reply
      • December 16, 2016 at 6:42 pm
        Permalink

        Hi,
        After i wrote above, i have updated android studio and suddenly everything worked…
        thanks a lot 🙂

        Reply
        • December 17, 2016 at 7:55 pm
          Permalink

          Glad it helped:)

          Reply
  • December 15, 2016 at 12:23 pm
    Permalink

    Hi…can you please explain how this can be done with the topic option in the Firebase console.

    Reply
    • December 16, 2016 at 2:59 pm
      Permalink

      Sure Nivedita:) I will try. Please give me some time. Thank You!

      Reply
  • January 4, 2017 at 4:12 pm
    Permalink

    Hello,

    I have followed your tutorial about Firebase Push Notifications.
    It’s very well explained and works perfectly.

    I just have a little problem, the notifications when app is closed work only after the second launch (and the others) and not after the first one. Do you have any idea why ?

    Thank you so much.

    Reply
  • January 9, 2017 at 5:03 pm
    Permalink

    I am following your tutorial , every goes right , I have a small query like ” how can I change msg text font size in on message recieved method ” is that possible, if possible please help me in doing this.

    Reply
  • January 19, 2017 at 5:31 am
    Permalink

    This is best tutorial for me

    Reply
    • January 22, 2017 at 5:05 am
      Permalink

      Thank You very much Deepa! Glad you liked it:)

      Reply
  • January 19, 2017 at 9:45 am
    Permalink

    is it possible to send image notification if the app is in foreground?? using Firebase console??

    Reply

Leave a Reply

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