Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that allows you to reliably send messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app.

Key Concepts

  1. Messages Types:

    • Notification Messages: These are messages that are displayed to the user. They can be sent from the Firebase console or via the FCM API.
    • Data Messages: These are messages that are handled by the client app. They are not visible to the user unless the app processes and displays them.
  2. Message Targeting:

    • Single Device: Send a message to a specific device using a unique device token.
    • Device Group: Send a message to a group of devices that belong to a single user.
    • Topic Messaging: Send a message to multiple devices that have opted into a particular topic.
    • Condition Messaging: Send a message to devices that satisfy a condition, such as being subscribed to multiple topics.
  3. Delivery Options:

    • Priority: Messages can be sent with normal or high priority.
    • Time to Live (TTL): Specifies how long (in seconds) the message should be kept in FCM storage if the device is offline.

Setting Up Firebase Cloud Messaging

Step 1: Add Firebase to Your Project

  1. Create a Firebase Project:

    • Go to the Firebase Console.
    • Click on "Add project" and follow the setup steps.
  2. Register Your App:

    • In the Firebase console, add your app to your Firebase project.
    • Follow the instructions to download the google-services.json (for Android) or GoogleService-Info.plist (for iOS) and add it to your project.

Step 2: Integrate FCM SDK

For Android:

  1. Add the Firebase SDK to Your Project:

    • Open your build.gradle file (project-level) and add the following:
      classpath 'com.google.gms:google-services:4.3.10'
      
    • Open your build.gradle file (app-level) and add the following:
      implementation 'com.google.firebase:firebase-messaging:23.0.0'
      apply plugin: 'com.google.gms.google-services'
      
  2. Initialize Firebase in Your Application:

    • In your MainActivity.java or MainActivity.kt, initialize Firebase:
      import com.google.firebase.FirebaseApp;
      
      public class MainActivity extends AppCompatActivity {
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              FirebaseApp.initializeApp(this);
              setContentView(R.layout.activity_main);
          }
      }
      

For iOS:

  1. Add the Firebase SDK to Your Project:

    • Add the following to your Podfile:
      pod 'Firebase/Messaging'
      
    • Run pod install to install the SDK.
  2. Initialize Firebase in Your Application:

    • In your AppDelegate.swift, initialize Firebase:
      import Firebase
      
      @UIApplicationMain
      class AppDelegate: UIResponder, UIApplicationDelegate {
          func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
              FirebaseApp.configure()
              return true
          }
      }
      

Sending Your First Message

Using Firebase Console

  1. Navigate to the Firebase Console:

    • Go to the Firebase console and select your project.
    • Click on "Cloud Messaging" in the left-hand menu.
  2. Compose a Message:

    • Click on "Send your first message".
    • Enter the message text and other details.
    • Select the target (e.g., a specific device, topic, etc.).
    • Click "Send".

Using FCM API

  1. Get Your Server Key:

    • In the Firebase console, go to "Project settings" > "Cloud Messaging".
    • Copy the "Server key".
  2. Send a Message via HTTP POST:

    • Use the following endpoint: https://fcm.googleapis.com/fcm/send.
    • Include the server key in the Authorization header.
    • Example request using curl:
      curl -X POST -H "Authorization: key=YOUR_SERVER_KEY" -H "Content-Type: application/json" -d '{
        "to": "DEVICE_TOKEN",
        "notification": {
          "title": "Hello",
          "body": "World"
        }
      }' https://fcm.googleapis.com/fcm/send
      

Practical Exercise

Exercise: Send a Notification Message

  1. Objective: Send a notification message to a specific device using the Firebase console.
  2. Steps:
    • Register your app with Firebase and integrate the FCM SDK.
    • Obtain the device token from your app.
    • Use the Firebase console to send a notification message to the device token.
  3. Expected Outcome: The device should receive and display the notification message.

Solution

  1. Obtain Device Token:

    • In your app, retrieve the device token:
      FirebaseMessaging.getInstance().getToken()
          .addOnCompleteListener(new OnCompleteListener<String>() {
              @Override
              public void onComplete(@NonNull Task<String> task) {
                  if (!task.isSuccessful()) {
                      Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                      return;
                  }
                  // Get new FCM registration token
                  String token = task.getResult();
                  Log.d(TAG, "FCM Token: " + token);
              }
          });
      
  2. Send Notification via Firebase Console:

    • Go to the Firebase console, navigate to "Cloud Messaging", and click "Send your first message".
    • Enter the message details and the device token obtained in the previous step.
    • Click "Send".

Conclusion

In this section, you learned about Firebase Cloud Messaging, its key concepts, and how to set it up in your project. You also learned how to send your first notification message using both the Firebase console and the FCM API. In the next section, we will dive deeper into sending notifications programmatically and handling them in your app.

© Copyright 2024. All rights reserved