0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Firebase Cloud Messaging (FCM) with Android

To use Firebase Cloud Messaging (FCM) with Android, add Firebase to your project, include the firebase-messaging library, and create a service extending FirebaseMessagingService to handle messages. Then, register your app with Firebase and use the Firebase console or server to send notifications.
📐

Syntax

Here is the basic syntax to set up FCM in an Android app:

  • Add Firebase Messaging dependency in build.gradle.
  • Create a class extending FirebaseMessagingService to receive messages.
  • Override onMessageReceived to handle incoming messages.
  • Use FirebaseMessaging.getInstance().getToken() to get the device token.
java
dependencies {
    implementation 'com.google.firebase:firebase-messaging:23.1.2'
}

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Handle FCM messages here.
    }

    @Override
    public void onNewToken(String token) {
        // Send token to your server if needed.
    }
}

// To get the token
FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(task -> {
        if (!task.isSuccessful()) {
            return;
        }
        String token = task.getResult();
        // Use or send token
    });
💻

Example

This example shows a complete minimal setup for receiving FCM messages in an Android app. It includes the service class and how to get the token.

java
dependencies {
    implementation 'com.google.firebase:firebase-messaging:23.1.2'
}

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getNotification() != null) {
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();
            // Show notification or handle message
            System.out.println("Notification Received: " + title + " - " + body);
        }
    }

    @Override
    public void onNewToken(String token) {
        System.out.println("New token: " + token);
        // Send token to your server if needed
    }
}

// In your main activity or initialization code
FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(task -> {
        if (!task.isSuccessful()) {
            System.out.println("Fetching FCM registration token failed");
            return;
        }
        String token = task.getResult();
        System.out.println("FCM Token: " + token);
    });
Output
Notification Received: Sample Title - Sample message body FCM Token: abc123xyz456token
⚠️

Common Pitfalls

Common mistakes when using FCM with Android include:

  • Not adding the google-services.json file to the app folder.
  • Forgetting to add the Firebase Messaging dependency.
  • Not declaring the FirebaseMessagingService in the AndroidManifest.xml.
  • Not handling the token refresh properly.
  • Trying to receive messages without internet permission.

Always check your Firebase project setup and app configuration.

xml
/* Wrong: Missing service declaration in AndroidManifest.xml */

<!-- No service tag for FirebaseMessagingService -->

/* Right: Add this inside <application> tag in AndroidManifest.xml */
<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
📊

Quick Reference

Key steps to use FCM with Android:

  • Add Firebase to your Android project via Firebase Console.
  • Download and add google-services.json to your app folder.
  • Add firebase-messaging dependency in build.gradle.
  • Create a service extending FirebaseMessagingService to handle messages.
  • Get the device token with FirebaseMessaging.getInstance().getToken().
  • Send notifications from Firebase Console or your server using the token.

Key Takeaways

Add Firebase and firebase-messaging dependency to your Android project.
Create a FirebaseMessagingService subclass to handle incoming messages.
Always include google-services.json and declare your service in AndroidManifest.xml.
Use FirebaseMessaging.getInstance().getToken() to get the device token for sending messages.
Test notifications using Firebase Console before integrating server-side messaging.