Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rich Targeted Push Notifications With Firebase

DZone's Guide to

Rich Targeted Push Notifications With Firebase

Learn how you can target specific users of your app then send them actionable push notifications with the power of Firebase and Google Analytics.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

Don’t be lazy. Don’t be one of those apps that sends boring, annoying, and useless push notifications. In this article, I will show you how to use Firebase to target a specific set of users and send them a valuable and actionable push notification as recommended by Android’s Best Practices Guidelines using my world class salad app. All source code is available on GitHub.

History

Push notifications have always been a pain in the bum. For anyone who has implemented a custom push notification system from scratch, you will appreciate the level of technical complexity involved in setting up the basic infrastructure to get a simple message from your backend to a device. And that’s before starting on the complexity of the business logic behind sending them to the correct user, at the correct time, with the correct content. The days of setting up certificates on backend servers, managing your users’ tokens and creating an interface for your marketing team are over. Thank god.

Parse was the biggest provider of this meta service until Facebook acquired and terminated its existence. Firebase picked up where Parse left off but quietly improved on the old toolbox without anyone noticing vis-a-vis integration with Google Analytics.

Sending No Message Is a Better Alternative to Sending the Wrong Message

Many apps are uninstalled before they are even used because the apps disturb users at the wrong time, with the wrong information. Instead of the user taking the intended action (i.e. to sit and explore the benefits of the app), the user usually sits and takes the time to uninstall the app completely, a surefire way to ensure that they aren’t disturbed again.

So, if you find yourself hovering over the red button that will broadcast a push notification to ALL of your users, it’s time to pause and reflect. You may be about to cull a good percentage of your userbase.

The Salad App Example

Ever started shopping on an online store, then been distracted and forgotten to check out? It’s a simple and common enough situation; there are potentially thousands of dollars sitting in virtual shopping carts, just begging to be ushered to the checkout. But how do you convince these users to finish shopping?

Recall the shopping cart I created with Firebase Realtime Database, let’s use this shopping cart along with Google Analytics to identify the users who need a gentle prod, and use push notifications to send an actionable and valuable notification to these users.

Step 1: Identify Your Target Segment

If you are savvy with Google Analytics, you will understand the marketing concept of customer segments, or Audiences. Creating an Audience involves grouping your users by one or more categories. In my example, I want to identify all people who are:

  1. Using my app.
  2. Who have one or more item in their shopping cart.
  3. Who have not used the shopping cart for two days or more.

To start, I need to add Google Analytics and Cloud Messaging to my app. Add these two lines to your build gradle file:

compile 'com.google.firebase:firebase-core:11.0.2'
compile 'com.google.firebase:firebase-messaging:11.0.2'

To gather the data on shopping carts, I’m going to use Google Analytics. I add two lines of code altering two User Properties whenever the user changes the shopping cart contents:

FirebaseAnalytics.getInstance(context).setUserProperty("shoppingCartCount", userDataHandler.shoppingCart.size.toString())
FirebaseAnalytics.getInstance(context).setUserProperty("shoppingCartLastUsed", System.currentTimeMillis().toString())

Now the Google Analytics section of the Firebase Console knows how many items are in each user's cart shoppingCartCount, and it knows when their cart was last used shoppingCartLastUsed. With these two small pieces of information, I’m ready to setup an Audience in the Firebase Console.

Image title

Stale Shopping Cart Audience.

Step 2: Test Your Assumption

Okay, now I can identify the users who have stale shopping carts. That’s enough information to sit back and monitor for a week or so. I don’t even want to continue down this path until I’m certain that there are enough people out there with a stale shopping cart to warrant spending extra effort on this little endeavor.

So a week passes, and you can see that there are hundreds of people who have stale carts. Time for the gentle prod.

Step 3: Send a Valuable and Actionable Push Notification

First, I need to setup the app so that it is able to receive push notifications.

The code for this is very similar to any other implementation of push notifications so I won't go into too much depth. The documentation is also very thorough and up to date. We have to do three things: create a concrete FirebaseInstanceIdService and FirebaseMessagingService. Then we need to write some code to create the notification itself. Then add these classes to the AndroidManifest.xml.

Don’t worry, all the code is available on GitHub.

The concrete class that will look after linking your device to Firebase:

package com.kan.salads.service

import com.google.firebase.iid.FirebaseInstanceIdService

class SaladFirebaseInstanceIDService : FirebaseInstanceIdService()

The familiar class that will handle all incoming messages from Firebase:

package com.kan.salads.service

import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v4.app.TaskStackBuilder
import android.support.v7.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.kan.salads.R
import com.kan.salads.activity.home.HomeActivity

class SaladFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage?) {
        super.onMessageReceived(remoteMessage)
        buildNotification(remoteMessage)
    }
}

The buildNotification() method inspects the contents of the RemoteMessage and creates a local notification that will appear in the user’s notification area of the pull-down menu in the operating system.

How you create this notification is also very important, but outside the scope of this article. Briefly, adding some intelligent options within the notification such as “Ask me later” (in case now isn’t a good time, as is often the case), “Don’t bother me again” (which is better than deletion), or “Take me to checkout.”

Image title

Smart inline options on a notification.

The Android Manifest also needs to know about these services so it can spin them up when it receives the messages:

<application>
  ...
    <service
        android:name=".service.SaladFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name=".service.SaladFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
</application>

Our app is now ready to receive push notifications. In the Firebase console, select “Notifications.” You are presented with a very simple to follow UI that enables you to select very specific User Segments. In this case, we want to send a push notification only to those people with stale shopping carts who have English as their system language. We could also use many of the automatic properties recorded by Firebase and Google Analytics — an important one being firebase_last_notification, which could be used to ensure that you don’t send more than one notification per day, for example.

Image title

The smaller the target, the more value you can add.

Now you have witnessed the power of Firebase at its zenith. Consider that it has taken you all of half an hour to: create a hypothesis, identify an incredibly narrow segment of users, test your assumption, construct a message, and send it. Pretty sweet, but we can do better.

Bonus #1: Internationalization

Notice that I’ve gone one step further and narrowed my audience down to all English speakers? Sending a German message out to English speakers is a big mistake and vice versa. Identifying your users’ language is hard enough; sending out the correct language is a tricky problem. Firebase makes this possible out of the box.

Bonus #2: Time Zone Handling

Image title

Target recipient time zone.

What good is sending someone a notification in the middle of the night? If you have a global user base, time zones are difficult problems for your devs to overcome.

Bonus #3: Validation

Okay, so now you’ve sent a push notification to everyone at 7 pm about their stale cart. But how do you know if this notification worked? Do you just watch sales go up? How do you know that the notification was a success? How do you know it was the cause of the spike? Correlation does not equal causality.

Image title

Conversion tracking. That’s covered, too.

Conclusion

Firebase contains many other standard features such as topic subscription, an API, sending key value pairs and prioritization. All good features, but nothing really new. The integration with Google Analytics really solidifies the position of Firebase as the first choice for push notifications in the mobile arena.

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
mobile ,mobile app development ,android ,firebase ,push notifications ,google analytics

Published at DZone with permission of Nick Skelton, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}