Push Notifications: Making your Android FCM client

Our Push Notifications system is currently in beta. This means you may experience errors, and the APIs may change. We would love to hear your feedback, so please get in touch!

Our Push Notifications API lets your Android applications subscribe to interests. When your servers send push notifications to those interests, the Android app will receive them. Your Android application can subscribe to interests using our pusher-websocket-android library (the same library you use for WebSockets). This page guides you through setting up your Android application to register, subscribe to interests, and receive push notifications pushed to those interests.

Prerequisites

You should already have an Android app which you would like to configure. For more on setting up an Android app with Pusher, see our Android Quick Start guide.

We’ll also assume that you followed these steps in the previous section on setting up FCM:

  • Get a Google Project on the Google Developers Console
  • Get a Server Key and submit it on the Pusher dashboard

Set up your google-services.json config file

The google-services.json file contains your Sender ID (a.k.a. Project Number), amongst other details. It should be placed in the app/ directory of your project.

You should have downloaded this file in the previous section. If not, visit the settings for your project.

Install the library

You can install the library via Gradle. First add these dependencies to your $PROJECT_ROOT/app/build.gradle. Also apply the google-services plugin at the bottom of your build.gradle:

dependencies {
  compile 'com.google.firebase:firebase-messaging:9.8.0'
  compile 'com.google.firebase:firebase-core:9.8.0'
  compile 'com.pusher:pusher-websocket-android:0.6.0'
}

apply plugin: 'com.google.gms.google-services'

In your project-level build.gradle add:

buildscript {
  dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
  }
}

Alter your manifest

Add Pusher’s FCM services. These allow the library to handle incoming tokens and keep state synced with our servers. To add these, just add the following to your AndroidManifest.xml:

<manifest>
  <!-- ... -->

  <application>
    <!-- ... -->

    <!-- Pusher's FCM listeners and services -->
      <service
          android:name="com.pusher.android.notifications.fcm.FCMMessagingService">
          <intent-filter>
              <action android:name="com.google.firebase.MESSAGING_EVENT"/>
          </intent-filter>
      </service>

      <service
          android:name="com.pusher.android.notifications.fcm.FCMInstanceIDService">
          <intent-filter>
              <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
          </intent-filter>
      </service>

    <!-- ... -->
  </application>

  <!-- ... -->
</manifest>

Register your app with Pusher

You can start registering for push notifications in an Activity or any other valid Context.

Expand your onCreate handler to instantiate a PusherAndroid, get the native push notification object from it, and call registerFCM, passing in the Context implementation:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        PusherAndroid pusher = new PusherAndroid(<pusher_api_key>);
        PushNotificationRegistration nativePusher = pusher.nativePusher();
        nativePusher.registerFCM(this);
    }
    // ...
}

Having called register, this will retrieve the FCM registration ID and upload it to Pusher. You can listen for the result of this registration by passing a PushNotificationRegistrationListener as a final argument:

nativePusher.registerFCM(this, new PushNotificationRegistrationListener() {
    @Override
    public void onSuccessfulRegistration() {
        System.out.println("REGISTRATION SUCCESSFUL!!! YEEEEEHAWWWWW!");
    }

    @Override
    public void onFailedRegistration(int statusCode, String response) {
        System.out.println(
                "A real sad day. Registration failed with code " + statusCode +
                        " " + response
        );
    }
});

Subscribe to an interest to receive push notifications

Each interest name can be up to 164 characters. Each character in the name must be an ASCII upper- or lower-case letter, a number, or one of _=@,.;. Note that the hyphen (-) is not a valid character in interest names. This character is reserved for the possibility in future of marking interest names with prefixes (such as private- or presence-).

Pusher has a concept of interests which clients can subscribe to. Whenever your server application sends a push notification to an interest, subscribed clients will receive those push notifications.

To subscribe to an interest, call:

PushNotificationRegistration nativePusher = pusher.nativePusher();
nativePusher.subscribe("donuts"); // the client is interested in donuts

To unsubscribe from an interest:

nativePusher.unsubscribe("donuts"); // we are no longer interested in donuts

You can also keep track of the state of your subscriptions or un-subscriptions by passing an optional InterestSubscriptionChangeListener:

nativePusher.subscribe("donuts", new InterestSubscriptionChangeListener() {
    @Override
    public void onSubscriptionChangeSucceeded() {
        System.out.println("Success! I love donuts!");
    }

    @Override
    public void onSubscriptionChangeFailed(int statusCode, String response) {
        System.out.println(":(: received " + statusCode + " with" + response);
    }
});

Listen for new push notifications

Finally, you should listen for new push notifications. You do this with setFCMListener:

nativePusher.setFCMListener(new FCMPushNotificationReceivedListener() {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
      // do something magical 🔮
    }
});

You’re all set up! Next, we’ll actually push a notification to the donuts interest, and your app will receive it. Let’s send some push notifications!

Have you tried using the search to find what you’re after? If you still have a question then get in touch with us and let us help you out.