Skip to content

GetSocial Notifications on Android

Prerequisite

Setup Android Push Notifications

GetSocial supports sending push notifications via Firebase Cloud Messaging (FCM) or Google Cloud Messaging (GCM).

  1. Follow FCM official guide (or GCM official guide) to setup push notifications in your app.

    CDM Permissions for GCM

    If you are using Google Cloud Messaging for Push Notifications, don’t forget to add CDM permissions to your AndroidManifest.xml:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    <application ...>
        ...
        <permission
            android:name="${applicationId}.permission.C2D_MESSAGE"
            android:protectionLevel="0x2" />
        <uses-permission
            android:name="android.permission.WAKE_LOCK" />
        <uses-permission
            android:name="com.google.android.c2dm.permission.RECEIVE" />
        <uses-permission
            android:name="${applicationId}.permission.C2D_MESSAGE" />
    </application>
    
  2. Login to the GetSocial Dashboard.

  3. Go to the “Notifications” section → “Settings” tab.
  4. Enable Android notifications by clicking on the switch and fill in “API Key” and “Sender ID” values.

    You can find “API Key” (Server key) and “Sender ID” in your application settings in Firebase developer console.

    GetSocial Dashboard - Enable Push Notifications

  5. Go to “Templates” tab and select what kind of notifications users will receive:

    GetSocial Dashboard - Notifications Type

  6. Press “Save” button in the bottom right corner.

  7. Check notifications texts and translations.

    GetSocial Dashboard - Check Notification Text

  8. Check setup sending a test notification to your test device.

    GetSocial Dashboard - Send Test Notification

Enable/disable GetSocial Notifications on the Client Side

By default GetSocial SDK automatically register at push server, and the user will start receiving push notifications

To prevent auto registration and register for push notifications manually:

  1. Add autoRegisterForPush property to the GetSocial configuration in the Android application build.gradle:

    1
    2
    3
    4
    getsocial {
        ...
        autoRegisterForPush false
    }
    
  2. To start receiving GetSocial push notifications call:

    1
    GetSocial.registerForPushNotification();
    

If you’re not using GetSocial Gradle Plugin check how to disable auto registration for push notifications in the Manual Integration Guide.

Handle Click on Push Notifications

Select Activity to Open

By default, click on the GetSocial notification will start launcher activity. If you want to open other activity on notification click, add the <intent-filter> with action getsocial.intent.action.NOTIFICATION_RECEIVE to the activity that should be opened:

1
2
3
4
5
6
7
<activity ...>
    ...
    <intent-filter>
        <action android:name="getsocial.intent.action.NOTIFICATION_RECEIVE"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

GetSocial UI

If you are using GetSocial UI, SDK will open respective view on click on the GetSocial notification. For instance, if someone liked your activity or commented under your activity, this activity will be shown on GetSocial notification click.

Important

If GetSocial View is opened automatically by GetSocial UI, you can not set the custom title, UiActionListener, action button handler, etc. In this case, we recommend you to override the default behavior and open GetSocial View by yourself.

Notification Listener

You can customize the default behavior and handle clicks on GetSocial notifications on your own. Also, you can listen for GetSocial notifications when an application is running in the foreground when the notification was received. To do so, set the NotificationListener in onCreate method of your Application or Activity:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
GetSocial.setNotificationListener(new NotificationListener() {

    public boolean onNotificationReceived(Notification notification, boolean wasClicked) {
        if (!wasClicked) {
            return false;
        }
        boolean isHandled = handleNotification(notification);
        return isHandled;
    }

});

wasClicked parameter is true when the application was opened by push notification click or false if the application was in the foreground when the notification was received.
In the example above return a boolean: true, if notification is handled by your method handleNotification(notification), or false if it is not. If you return false, SDK will handle the notification.

For example, if you want to prevent of showing GetSocial Activity Feed UI on notification click:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
boolean handleNotification(Notification notification) {
    switch (notification.getActionType()) {
        case Notification.ActionType.OPEN_ACTIVITY:
            // add custom logic here
            Log.i("GetSocial", "Activity Notification received");
            return true;

        default:
            return false;
    }
}

Tip

If you are not using GetSocial UI, we recommend to handle notifications by yourself - better user experience would be to react to notification actions.

Show Notifications In Foreground

If you want to show GetSocial notifications while app is in foreground - set foregroundNotifications to true in the GetSocial configuration in your build.gradle:

1
2
3
4
getsocial {
    ...
    foregroundNotifications true
}

If you’re not using GetSocial Gradle Plugin check how to enable foreground notifications in the Manual Integration Guide.

If foregroundNotifications is set to true:

  • Notifications will be shown when your application is in foreground.
  • NotificationListener will be called after clicking on the notification; parameter wasClicked will be true.

Get Notifications

To be sure your users didn’t miss any important(or not) notifications, you can query GetSocial notifications and show it to your user inside the app. Or send it once again as local notification. Or handle it in any other convenience method.

Query

You have two types of queries: NotificationQuery and NotificationsCountQuery to get notifications list and notifications count respectively.

Notification can differ by a read status - be read or unread. Also each notification has type, it is one of Notification.NotificationType constants.

To query notifications by a read status, use one of static factory methods read(), unread() or readAndUnread().

By default notifications of all types are queries. Also you can explicitly call ofAllTypes() to be sure that all types are queries. To specify a list of types you’re interested in call method ofTypes(Notification.NotificationType... types) and pass one or few types you want to query.

Notifications Count

To get the count of notifications use GetSocial.User.getNotificationsCount(query, callback) method. For example, to get a number of all unread notifications for current user:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
NotificationsCountQuery query = NotificationsCountQuery.unread().ofAllTypes();
GetSocial.User.getNotificationsCount(query, new Callback<Integer>() {
    @Override
    public void onSuccess(Integer count) {
        Log.d("Notifications", "Unread notifications count: " + count);
    }

    @Override
    public void onFailure(GetSocialException exception) {
        Log.e("Notifications, "Failed to get notifications count: " + exception);
    }
});

Notifications List

Similar to notifications count you can fetch a list of notifications using GetSocial.User.getNotifications(query, callback) mehtod:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
NotificationsQuery query = NotificationsQuery.unread().ofAllTypes();
GetSocial.User.getNotifications(query, new Callback<List<Notification>>() {
    @Override
    public void onSuccess(List<Notification> notifications) {
        showNotifications(notifications);
    }

    @Override
    public void onFailure(GetSocialException exception) {
        Log.e("Notifications, "Failed to get notifications: " + exception);
    }
});

Read And Unread Notifications

All the notifications that are sent to a user are unread. The only exception is notifications that was clicked by a user - such becomes read automatically.

If you want to set notification read or unread use GetSocial.User.setNotificationsRead(notificationIds, isRead, callback) method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
List<Notification> notificationsToBeRead = ...;
List<String> notificationIds = new ArrayList<String>();
for (Notification notification : notificationsToBeRead) {
    notificationIds.add(notification.getId());
}
boolean markAsRead = true;
GetSocial.User.setNotificationsRead(notificationIds, markAsRead, new CompletionCallback() {
    @Override
    public void onSuccess() {
        Log.d("Notifications, "Successfully changed notifications status");
    }
    @Override
    public void onFailure(GetSocialException exception) {
        Log.e("Notifications, "Failed to change notifications status: " + exception);
    }
});

You can mark just one notification using Collections.singletonList(notification.getId()).

Disable Push Notifications For User

If you don’t want to send notifications to a user, use GetSocial.User.setPushNotificationsEnabled(false, callback). Notifications will still appear in the notification center. To enable it back use GetSocial.User.setPushNotificationsEnabled(true, callback).

To check current setting value use GetSocial.User.isPushNotificationsEnabled(callback).

Send Notification

You can also send notifications directly from the SDK to other users just in few lines of code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
String text = String.format("Hello, %s! Greetings from %s.", SendNotificationPlaceholders.CustomText.RECEIVER_DISPLAY_NAME, SendNotificationPlaceholders.CustomText.SENDER_DISPLAY_NAME);
NotificationContent notification = NotificationContent.notificationWithText(text).withTitle("Greetings!");
List<String> receivers = Arrays.asList(SendNotificationPlaceholders.Receivers.REFERRED_USERS, SendNotificationPlaceholders.Receivers.REFERRER);
GetSocial.User.sendNotification(receivers, notification, new Callback<NotificationsSummary>() {
    @Override
    public void onSuccess(NotificationsSummary result) {
        Log.d(TAG, "Successfully sent "  + result.getSuccessfullySentCount() + " notifications!");
    }

    @Override
    public void onFailure(GetSocialException exception) {
        Log.d(TAG, "Failed to send notification, error: " + exception.getMessage());
    }
});

This example shows how to send message with dynamic text and title to all the users, whom you invited and the one who invited you.

Receivers

  • Receivers list can not be empty.
  • It may contain up to 25 different user IDs and one or many placeholders from SendNotificationPlaceholders.Receivers.
  • If you will send more that 25 user IDs - method will fail and no notifications will be sent.
  • If you mentioned one user twice or user is in two or more placeholder groups - the notification will be sent only once.
  • If our service can not send the notification to one or many users, it will be delivered to all other users. You can check the number of successfully sent notifications in the response.

Notification Content

There are three ways to create a notification content:

  • Dynamically create all the content on the SDK.
  • Use one of the GetSocial templates and override template placeholders.
  • Create your own template and override template placeholders.

Tip

You still can override any content when using the template notification.

  • To create a notification with text use NotificationContent.notificationWithText(String text).
  • Add a title using notification.withTitle(title) method.
  • You can add one or few default placeholders from the SendNotificationPlaceholders.CustomText to both title and text.

Template Notification

To create a template for notifications:

  1. Login to the GetSocial Dashboard.

  2. Go to the “Notifications” section → “Templates” tab.

  3. Press “New Template” button.

    GetSocial Dashboard - Create New Template

  4. Create a new template by giving a unique name and meaningful description.

  5. Setup the notification content. You can add translations, emojis, default placeholders(Sender/Receiver display name) or custom placeholders that can be replaced on the SDK. Also you can set the fallback value for each placeholder which will be taken if it wasn’t sent from the SDK side.

  6. To check the list of your custom templates switch to “Custom” tab using radio button.

Now create and setup notification using GetSocial Android SDK:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Text for the template "new_level_achieved" on the Dashboard:
// "Your friend [SENDER_DISPLAY_NAME] just reached [USER_LEVEL] lvl! Try to beat his score!"

NotificationContent notification = NotificationContent.notificationFromTemplate("new_level_achieved");
... // set up your notification
notification.addTemplatePlaceholder("USER_LEVEL", "7"); // add replacement for your placeholders without brackets

GetSocial.User.sendNotification(users, notification, callback);
// Your recipients will receive text:
// "Your friend John Doe just reached 7 lvl! Try to beat his score!"

[SENDER_DISPLAY_NAME] is automatically replaced with sender display name.

Action

To set an action to the notification click, use notification.withAction(int action). int action is one of Notification.ActionType constants. By default it is Notification.ActionType.CUSTOM.

Add action data using addActionData(String key, String val) or addActionData(Map<String, String> map) - second one will add all the keys and values from parameter map. For the default GetSocial actions use one of Notification.Key constants to guarantee the default behaviour. Also you can pass any custom data you want and handle it on the receiver side.

You can send any of predefined actions that will be handled by the SDK, for example to open Activity Feed with id “funny-stories” use:

1
2
3
NotificationContent notification = NotificationContent.notificationWithText("Hey, join the channel with funny stories and tell yours!")
    .withAction(Notification.ActionType.OPEN_ACTIVITY)
    .addActionData(Notification.Key.OpenActivity.FEED_NAME, "funny-stories");

You can send custom action with custom action data and handle it by your own using Notification Listener.

GetSocial Actions

  1. Open User Profile.

    Notification.ActionType.OPEN_PROFILE is not handled by SDK but you can handle it with Notification Listener. Parameters:

    • Notification.OpenProfile.USER_ID - GetSocial user ID whose profile should be opened.
  2. Open Activity Feed.

    Notification.ActionType.OPEN_ACTIVITY is handled by SDK. Will open activity feed with provided name, or activity feed post itself or scroll to the certain comment if provided. Parameters:

    • Notification.OpenActivity.ACTIVITY_ID - Activity Feed post ID.
    • Notification.OpenActivity.COMMENT_ID - Comment under that activity. Optional.

    or:

    • Notification.OpenActivity.FEED_NAME - Feed to Open. Use ActivitiesQuery.GLOBAL_FEED to open global feed.
  3. Open Smart Invites.

    Notification.ActionType.OPEN_INVITES is handled by SDK. Will open Smart Invites screen. Has no required parameters.

  4. Open URL.

    Notification.ActionType.OPEN_URL is handled by SDK. Wil open a system web browser with provided URL. Parameters:

    • Notification.OpenUrl.URL - URL to open.

Image/Video Content

It’s possible to send image and video content in notification.
You can set image or video using NotificationContent.withMediaAttachment().

1
2
3
MediaAttachment attachment = ... ;
NotificationContent notificationContent = NotificationContent.notificationWithText("Check this cool image!")
                        .withMediaAttachment(attachment);

You can create different types of attachments using MediaAttachment.image(Bitmap image) for image, MediaAttachment.video(byte[] video) for a video, MediaAttachment.imageUrl(String imageUrl) for images’ remote url or MediaAttachment.videoUrl(String videoUrl) or videos’ remote url.

Customize Notification Icon

By default, GetSocial SDK will use application icon as the notification icon.

There are two ways to customize the icon. The first option is to put an image with name getsocial_notification_icon into res/drawable folder.

If you want to use an existing icon for notifications, you can set the resource name in the Android Manifest. For instance to use ic_notification_custom.png from res/drawable:

1
2
3
4
5
6
7
<application ... >
    ...
    <meta-data
        android:name="im.getsocial.sdk.NotificationIcon"
        android:resource="@drawable/ic_notification_custom" />
    ...
</application>

As a result all notifications coming from GetSocial SDK will use custom icon:

Customized Notification Icon

Also, you can customize large notification icon using manifest. To use ic_large_notification_icon.png from res/drawable:

1
2
3
4
5
6
7
<application ... >
    ...
    <meta-data
        android:name="im.getsocial.sdk.LargeNotificationIcon"
        android:resource="@drawable/ic_large_notification_icon" />
    ...
</application>

Customized Notification Icon

Customize Notifications Channel

All GetSocial notifications come to separate notifications channel with ID getsocial_channel_id. By default, channel is called Social and has empty description. Name is localized to all GetSocial supported languages.

To customize channel name or description, add the following meta data pointing to the string resource to AndroidManifest.xml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<application ... >
    ...
    <meta-data
        android:name="im.getsocial.sdk.NotificationsChannelTitle"
        android:resource="@string/getsocial_notifications_channel_title" />

    <meta-data
        android:name="im.getsocial.sdk.NotificationsChannelDescription"
        android:resource="@string/getsocial_notifications_channel_description" />
    ...
</application>

To check your customization, on your phone (Android O, API 26 and higher) go to SettingsApps and Notifications[YOUR APP NAME]Notifications and find your channel. Description can be checked after pressing the channel name at the bottom of the screen.

Next Steps

Give us your feedback! Was this article helpful?

😀 🙁