Firebase Cloud Messaging – How to Receive Messages | Android

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that help us deliver messages reliably at no cost. In this tutorial, we’re gonna look at way to receive Messages in an Android App using FCM.

I. Firebase Cloud Messaging

1. Usage

With FCM, we can:
– notify a client that new data is available to sync.
– send notification messages to drive user re-engagement and retention.
– create instant messaging with a payload of up to 4KB to a client app.

2. How to receive Messages
2.1 Add Firebase Config file

Follow this guide to generate google-services.json file and move it into your Android App root directory. You don’t need to get SHA-1 Key in this example.

2.2 Add dependencies

build.gradle (project-level):

build.gradle (App-level):

2.3 Extend FirebaseMessagingService

Create class that inherits FirebaseMessagingService class and override onMessageReceived() method:

2.4 Android Manifest

For Firebase Service:

II. Practice

1. Goal

We will build an Android App that can:
– receive Message when running
– get Notification payload and Data payload

To send notification messages, we use Notifications Composer in the Firebase Console.

2. Technology

– Gradle 2.3.3
– Android Studio 2.x
– Firebase Android SDK 11.x

3. Project Structure

firebase-cloud-messaging-project-structure

4. Step by step
4.1 Create Android Project

– Generate new Android Project with package com.javasampleapproach.fcm.
build.gradle (project-level):

build.gradle (App-level):

4.2 Create Firebase Project & Add Firebase Config file

– Follow this guide to generate google-services.json file and move it into your Android App root directory. You don’t need to have SHA-1 Key in this example, just leave it blank.

– Make sure that package_name in google-services.json has a correct value according to:
+ applicationId in build.gradle (App-level).
+ package in AndroidManifest.xml.
In this case, it is com.javasampleapproach.fcm.

4.3 Create class for handling messages

Inside com.javasampleapproach.fcm package, create MyFCMClass:

4.4 Add Firebase Service to AndroidManifest

4.5 Run & Check result

– Use Android Studio, build and Run your Android App.

– Go to Firebase Console, click on the Project that you created above. Click on Notification in the left menu of the site.

– Compose Message:
firebase-cloud-messaging-compose-message

More data:
firebase-cloud-messaging-compose-message-2

Click on SEND MESSAGE.

– Return to Android Studio:
firebase-cloud-messaging-result

III. Source code

FCM-receiveMessages


Related Posts


Got Something To Say:

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

*