Navigation

Push Notifications (Android App)

Overview

This tutorial demonstrates how to use MongoDB Stitch to receive push notifications in an Android app.

Prerequisites

You must have the following before beginning this tutorial:

  • Android Studio or another Android development IDE.

  • A Google Developer account.

  • A local copy or clone of the stitch-examples GitHub repository.
    This tutorial uses the StitchSamplePushNotificationApp directory within this repository.

Procedure

A. Create and Configure a Firebase Project

  1. Log on to https://console.firebase.google.com/.

  2. Click Add Project to create a new project. You will be prompted for a project name, after which a project ID is automatically created.

  3. Click the Create Project button.

    Upon successful creation, click the Continue button, and you will be redirected to your Firebase project overview page.

  4. At the top of the left-side navigation, next to Project Overview, click the gear icon, and then select Project Settings.

  5. In the Project Settings page, select the Cloud Messaging tab.

    Important

    Make note of the Legacy server key and Sender ID fields, as you will use them when configuring your Stitch application in later steps.

  6. Select the General tab.

  7. Click the Add Firebase to your Android app button.

  8. In the Android package name field, enter com.mongodb.example.pushnotification, and then click the Register App button.

    Important

    Make note of the App ID, as you will need to provide it when configuring your Android app.

  9. Click the google-services.json button to download your Firebase configuration file. Place this google-services.json file in the app/ directory of your Android project directory.

You are now finished configuring Firebase for this project.

B. Set up the Example Android App

  1. In Android Studio, open the app contained in the directory StitchSamplePushNotificationApp.

  2. Edit the strings.xml file located in app/src/main/res/values, and update the following keys:

    stitch_client_app_id The App ID for your Stitch app. Your App ID can be found on the Clients page of the Stitch console.
    fcm_sender_id The Sender ID of your Firebase application.
    fcm_app_id The App ID of your Firebase application.
    <resources>
       <string name="app_name">Stitch Sample Push Notification App</string>
       <string name="subscribe_holidays">holidays</string>
       <string name="subscribe_quotes">quotes</string>
       <string name="subscribe_events">events</string>
       <string name="btn_subscribe">Update Subscriptions</string>
       <string name="stitch_client_app_id">TBD</string>
       <string name="fcm_sender_id">TBD</string>
       <string name="fcm_app_id">TBD</string>
    </resources>
    
  3. Run the App in an Android emulator or phone supporting SDK version 21 or higher. The app, when running, should look like the following image:

    The Example App Running
  4. Select one or more topics to subscribe to the notifications for that specific topic.

C. Create and Configure a MongoDB Stitch Application

  1. Log in to Atlas and create a new MongoDB Stitch app. If you have not set up an Atlas cluster or a MongoDB Stitch application, see steps in Getting Started.
  2. In the Stitch console, select Push Notifications in the left navigation pane.
  3. Select the Config tab.
  4. In the Sender ID field, enter your Firebase project’s Sender ID.
  5. In the API Key field, enter your Firebase project’s Legacy server key.
  6. Click Save.

D. Create Push Notifications in MongoDB Stitch

  1. In the Push Notifications section, click the Send New Notification button.

  2. Create a new notification message by providing the message text (limited to 250 characters), a message label, and a topic that has been subscribed to in the app (either “holidays”, “quotes”, or “events”).

  3. Click Send Message.

    Note

    If you receive an error message within the Stitch console, wait a few minutes and try again. There may be a delay in the initial app registration with Firebase. You should also ensure that the topic you specified is one of the above values, with no special characters.

  4. If the app has subscribed to the topic, a notification will appear in the system tray:

    A new notification has been received

About the Code

The Firebase listener service is specified in the AndroidManifest.xml file:

<!-- Name of your Firebase ListenerService -->
<service
    android:name=".MyFirebaseMessagingService"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

The method onMessageReceived in MyFirebaseMessagingService is called when messages from subscribed topics are received. When a message is received, Firebase creates a system tray notification.

In MainActivity.java the following subscribes to the topic described by the checkbox label:

if (checkBox.isChecked()) {
     FirebaseMessaging.getInstance().subscribeToTopic(topic).addOnCompleteListener(new OnCompleteListener<Void>() {
         @Override
         public void onComplete(@NonNull final Task<Void> task) {
             if (!task.isSuccessful()) {
                 Log.d(TAG, "Error subscribing to topic " + task.getException());
                 return;
             }

             Log.d(TAG, "Subscribed to topic " + topic);
             Toast.makeText(getApplicationContext(), "Subscribed to topic " + topic, Toast.LENGTH_LONG).show();
         }
     });
 }