Handling Push Notifications in Android

improve this page | report issue

Overview

Before Android applications are able to handle any received push notifications, support for Google Play Services needs to be configured. Once an application has been configured, MobileFirst-provided Notifications API can be used in order to register & unregister devices, and subscribe & unsubscribe to tags. In this tutorial, you will learn how to handle push notification in Android applications.

Prerequisites:

Jump to:

Notifications Configuration

Create a new Android Studio project or use an existing one.
If the MobileFirst Native Android SDK is not already present in the project, follow the instructions in the Adding the Mobile Foundation SDK to Android applications tutorial.

Project setup

Google Cloud Messaging (GCM) has been discontinued and is integrated with Firebase Cloud Messaging (FCM).

Setting up an application in FCM is a bit different compared to the old GCM model.

  1. To use Firebase messaging, you need a google-services.json file. Click here for documentation on how to get it.
    • In Add Firebase to your Android app window, use com.ibm.mobilefirstplatform.clientsdk.android.push as the Package Name.
  2. In Android → Gradle scripts, select the build.gradle (Module: app) file and add the following lines to dependencies: xml implementation group: 'com.ibm.mobile.foundation', name: 'ibmmobilefirstplatformfoundationpush', version: '8.0.+', ext: 'aar', transitive: true

    Or in a single line: xml implementation 'com.ibm.mobile.foundation:ibmmobilefirstplatformfoundationpush:8.0.+'

    Note: If you are using Google Dynamic Delivery feature and would like to call MobileFirst APIs in a feature module then use api declaration instead of implementation. Using implementation would restrict using MobileFirst APIs in the same module itself while using api would make MobileFirst APIs available across all modules present in the app including feature modules.For more details read API and implementation separation.

 api 'com.ibm.mobile.foundation:ibmmobilefirstplatformfoundationpush:8.0.+'
  1. Configure your Gradle file. Add the following to the app’s build.gradle file

    dependencies {
       ......
       compile 'com.google.firebase:firebase-messaging:17.6.0'
       .....
    }
    
    apply plugin: 'com.google.gms.google-services'
    
    • Add the following dependency to the root build.gradle file’s buildscript section
      classpath 'com.google.gms:google-services:3.0.0'
      

    Note: If you are using Android Studio v3.2 or earlier, make sure that each dependency line only has one version number specified.

  2. In Android → app → manifests, open the AndroidManifest.xml file.
    • Add the following permissions to the top the manifest tag:

      	<!-- Permissions -->
      		<uses-permission android:name="android.permission.WAKE_LOCK" />
      
    • Add the following to the application tag:

      ```xml

      	<!-- MFPPush Intent Service -->
      
      <!-- MFPPush Instance ID Listener Service -->
       		<service android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        	</intent-filter>
        	</service>
      
    <activity android:name=”com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushNotificationHandler”
        android:theme="@android:style/Theme.NoDisplay"/>    ```  * Add the following `intent-filter` to the application's activity.
    

    ```xml

    ```

    Note: Be sure to replace your.application.package.name with the actual package name of your application.

  3. Open the app in Android Studio. Copy the google-services.json file that you have created in the step-1 inside the app directory. Note that the google-service.json file includes the package name you have added.

  4. Compile the SDK. Build the application.

Notifications API

MFPPush Instance

All API calls must be called on an instance of MFPPush. This can be done by creating a class level field such as private MFPPush push = MFPPush.getInstance();, and then calling push.<api-call> throughout the class.

Alternatively you can call MFPPush.getInstance().<api_call> for each instance in which you need to access the push API methods.

Challenge Handlers

If the push.mobileclient scope is mapped to a security check, you need to make sure matching challenge handlers exist and are registered before using any of the Push APIs.

Learn more about challenge handlers in the credential validation tutorial.

Client-side

Java Methods Description
initialize(Context context); Initializes MFPPush for supplied context.
isPushSupported(); Does the device support push notifications.
registerDevice(JSONObject, MFPPushResponseListener); Registers the device with the Push Notifications Service.
getTags(MFPPushResponseListener) Retrieves the tag(s) available in a push notification service instance.
subscribe(String[] tagNames, MFPPushResponseListener) Subscribes the device to the specified tag(s).
getSubscriptions(MFPPushResponseListener) Retrieves all tags the device is currently subscribed to.
unsubscribe(String[] tagNames, MFPPushResponseListener) Unsubscribes from a particular tag(s).
unregisterDevice(MFPPushResponseListener) Unregisters the device from the Push Notifications Service

Initialization

Required for the client application to connect to MFPPush service with the right application context.

  • The API method should be called first before using any other MFPPush APIs.
  • Registers the callback function to handle received push notifications.
MFPPush.getInstance().initialize(this);

Is push supported

Checks if the device supports push notifications.

Boolean isSupported = MFPPush.getInstance().isPushSupported();

if (isSupported ) {
    // Push is supported
} else {
    // Push is not supported
}

Register device

Register the device to the push notifications service.

MFPPush.getInstance().registerDevice(null, new MFPPushResponseListener<String>() {
    @Override
    public void onSuccess(String s) {
        // Successfully registered
    }

    @Override
    public void onFailure(MFPPushException e) {
        // Registration failed with error
    }
});

Get tags

Retrieve all the available tags from the push notification service.

MFPPush.getInstance().getTags(new MFPPushResponseListener<List<String>>() {
    @Override
    public void onSuccess(List<String> strings) {
        // Successfully retrieved tags as list of strings
    }

    @Override
    public void onFailure(MFPPushException e) {
        // Failed to receive tags with error
    }
});

Subscribe

Subscribe to desired tags.

String[] tags = {"Tag 1", "Tag 2"};

MFPPush.getInstance().subscribe(tags, new MFPPushResponseListener<String[]>() {
    @Override
    public void onSuccess(String[] strings) {
        // Subscribed successfully
    }

    @Override
    public void onFailure(MFPPushException e) {
        // Failed to subscribe
    }
});

Get subscriptions

Retrieve tags the device is currently subscribed to.

MFPPush.getInstance().getSubscriptions(new MFPPushResponseListener<List<String>>() {
    @Override
    public void onSuccess(List<String> strings) {
        // Successfully received subscriptions as list of strings
    }

    @Override
    public void onFailure(MFPPushException e) {
        // Failed to retrieve subscriptions with error
    }
});

Unsubscribe

Unsubscribe from tags.

String[] tags = {"Tag 1", "Tag 2"};

MFPPush.getInstance().unsubscribe(tags, new MFPPushResponseListener<String[]>() {
    @Override
    public void onSuccess(String[] strings) {
        // Unsubscribed successfully
    }

    @Override
    public void onFailure(MFPPushException e) {
        // Failed to unsubscribe
    }
});

Unregister

Unregister the device from push notification service instance.

MFPPush.getInstance().unregisterDevice(new MFPPushResponseListener<String>() {
    @Override
    public void onSuccess(String s) {
        disableButtons();
        // Unregistered successfully
    }

    @Override
    public void onFailure(MFPPushException e) {
        // Failed to unregister
    }
});

Handling a push notification

In order to handle a push notification you will need to set up a MFPPushNotificationListener. This can be achieved by implementing one of the following methods.

Option One

In the activity in which you wish the handle push notifications.

  1. Add implements MFPPushNofiticationListener to the class declaration.
  2. Set the class to be the listener by calling MFPPush.getInstance().listen(this) in the onCreate method.
  3. Then you will need to add the following required method:

    @Override
    public void onReceive(MFPSimplePushNotification mfpSimplePushNotification) {
         // Handle push notification here
    }
    
  4. In this method you will receive the MFPSimplePushNotification and can handle the notification for the desired behavior.

Option Two

Create a listener by calling listen(new MFPPushNofiticationListener()) on an instance of MFPPush as outlined below:

MFPPush.getInstance().listen(new MFPPushNotificationListener() {
    @Override
    public void onReceive(MFPSimplePushNotification mfpSimplePushNotification) {
        // Handle push notification here
    }
});

Migrating to FCM SDK v19.x

For an existing application using old version of FCM SDK, to use latest FCM SDK v19.x and above you need to migrate the android project to AndroidX. Please add below to the application.

  1. In the app’s build.gradle file

    • Remove below dependencies from the build.gradle file

      ```
       		dependencies {
      		...
      		implementation 'com.android.support:appcompat-v7:28.0.0'
       				implementation 'com.android.support:design:28.0.0'
        		implementation 'com.android.support:support-v4:28.0.0'
            implementation 'com.google.firebase:firebase-messaging:17.6.0' 
            ...
            }   ```
      
    • Replace with below dependencies

      ```
      	dependencies {
       			 ...
      		implementation "com.google.firebase:firebase-messaging:20.0.0"
            implementation "androidx.appcompat:appcompat:1.1.0'"
            implementation "androidx.legacy:legacy-support-v4:1.0.0"
            implementation "com.google.android.material:material:1.1.0"
            ...
        }   ```
      
  2. Configure the AndroidManifest file. Following changes are required in the AndroidManifest.xml

    • The below entries need modification :

        <service android:exported="true" android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushIntentService">
            <intent-filter>
        		<action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
      
    • Modify the entries to :

        <service android:exported="true" android:name="com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushNewIntentService">
            <intent-filter>
        		<action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
      

Image of the sample application

Sample application

Click to download the Android Studio project.

Sample usage

Follow the sample’s README.md file for instructions.

Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on July 02, 2020