While building your app to provide a great experience is incredibly important, engaging with new and existing users is even more important to the long-term success of your app. In this tutorial you will learn how to use Firebase to enable Google Cloud Messaging and send notifications to your app, as well as how to allow users to share your app with their contacts who use either Android or iOS devices.
This tutorial will assume that you have already set up a project for Firebase and have access to the Firebase Console. To learn how to get started with Firebase for Android, check out one of our other tutorials:
Firebase Notifications
Notifications are one of the easiest ways to let your users know about new events or features in your app and get them to open the app again. Using Firebase, you can send notifications to all users or to segments of your user base, allowing you to customize what your users receive and pique their interest.
Notifications While Your App Is in the Background
Displaying notifications when your app is in the background is incredibly easy, as it is handled automatically by the Firebase Messaging library. In your application, you will need to include the library with the following line in the dependencies
node of your build.gradle file, and then install the app on a device.
compile 'com.google.firebase:firebase-messaging:9.8.0'
Next, you'll need to go into your Firebase console and select the Notifications section in the left navigation panel.
Once you're in the correct section, you should see a screen prompting you to send your first message.
Once you have clicked on the blue button, you will be taken to a form that will allow you to add content to messages and select which groups should receive the message. Using this form, you can specify boolean conditions that a device or user must meet—such as geographical location or any other gathered data—in order to receive your notification.
Once you have sent the message, a notification should appear on your user's devices.
Notifications in the Foreground
One thing to notice is that notifications won't show up for a user if they are already in your app. In order to receive notifications in this situation, you will need to implement a Service
that extends FirebaseMessagingService
.
public class NotificationService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); } }
You will also need to include this Service
in your AndroidManifest.xml file.
<service android:name=".NotificationService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>
Now that you have the general framework together, it's time to flesh out onMessageReceived
in your FirebaseMessagingService
class. The main purpose of this method is to take the data sent down with the RemoteMessage
object and create a Notification
based on what you receive.
There's a lot of information that can be passed down with the RemoteMessage
. However, most of the options are only available if you use the Firebase back-end API, rather than the console. From the Firebase console, you are able to set a title, a message body, and custom key/value pairs.
Logging all of the available data from a RemoteMessage
can be done like so:
for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) { Log.e("Test", "Key = " + entry.getKey() + ", Value = " + entry.getValue() ); } Log.e("TutsPlus", "collapsekey: " + remoteMessage.getCollapseKey()); Log.e("TutsPlus", "from: " + remoteMessage.getFrom() ); Log.e("TutsPlus", "message id: " + remoteMessage.getMessageId() ); Log.e("TutsPlus", "message type:: " + remoteMessage.getMessageType() ); Log.e("TutsPlus", "to: " + remoteMessage.getTo() ); Log.e("TutsPlus", "send time: " + remoteMessage.getSentTime() ); Log.e("TutsPlus", "ttl: " + remoteMessage.getTtl() ); Log.e("TutsPlus", "title: " + remoteMessage.getNotification().getTitle() ); Log.e("TutsPlus", "body: " + remoteMessage.getNotification().getBody() ); Log.e("TutsPlus", "click action: " + remoteMessage.getNotification().getClickAction() ); Log.e("TutsPlus", "color: " + remoteMessage.getNotification().getColor() ); Log.e("TutsPlus", "icon: " + remoteMessage.getNotification().getIcon() );
Which, in turn, will produce the following log messages.
E/TutsPlus: Key = custom_data_key, Value = some_value E/TutsPlus: collapsekey: com.tutsplus.tutsplusfirebasenotification E/TutsPlus: from: 1044252370931 E/TutsPlus: message id: 0:1478812920837872%ba5f8433ba5f8433 E/TutsPlus: message type:: null E/TutsPlus: to: null E/TutsPlus: send time: 1478812919847 E/TutsPlus: ttl: 0 E/TutsPlus: title: Custom title E/TutsPlus: body: Message Text E/TutsPlus: click action: null E/TutsPlus: color: null E/TutsPlus: icon: null
Once you know what information is available, and how you want to handle it, you can create and display a notification for your users.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle(remoteMessage.getNotification().getTitle()); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentText(remoteMessage.getNotification().getBody()); NotificationManagerCompat.from(this).notify(0, builder.build());
And that's it! You should now be able to set up an Android app to send and receive notifications from the Firebase console.
App Invites
Getting new users on your app can be a daunting challenge, but word of mouth is a great way to get the ball rolling. Using Firebase, you can add the App Invites widget to your application, which will let your users share your app via email or SMS to other Android or iOS users.
Launching the Invite Prompt
Before you can start using this feature, you will need to import the package into your project by adding the following line to the dependencies
node of your build.gradle file.
compile 'com.google.firebase:firebase-invites:9.8.0'
Once you have synced your project, you will be able to create a new Intent
using the AppInviteInvitation.IntentBuilder
class, which will launch a screen that allows users to select contacts to invite to the app. This builder provides various options for customizing the app invite screen:
-
setMessage
: This will set the message that users see and can send to contacts over text message or email. This cannot be longer than 100 characters. -
setCustomImage
: Using this method, you can provide a URI to a custom image that will appear in the invite screen and invite email. -
setCallToActionText
: This method sets the text for the install button in emails. This has a limit of 32 characters. -
setDeepLink
: Allows you to provide metadata for your invite, which can be received on install for taking specific actions for your newly invited user. -
setEmailHtmlContent
: Allows you to overridesetMessage
,setCustomImage
, andsetCallToActionText
to create a custom HTML formatted email to send to potential new users. -
setEmailSubject
: Required ifsetEmailHtmlContent
is used. As the name implies, this will set the subject for your custom email. -
setOtherPlatformsTargetApplication
: One of the more interesting options, this method will allow you to associate the Firebase client app ID for an iOS version of your app, allowing iOS users to install the proper version if it's shared by an Android user.
Once you've created your Intent
, you can launch it with startActivityForResult
to be notified when the user has returned from inviting others.
Intent intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title)) .setMessage(getString(R.string.invitation_message)) .setCustomImage(Uri.parse(getString(R.string.invitation_custom_image))) .setCallToActionText(getString(R.string.invitation_cta)) .setDeepLink(Uri.parse("/link")) .setOtherPlatformsTargetApplication( AppInviteInvitation.IntentBuilder.PlatformMode.PROJECT_PLATFORM_IOS, getString(R.string.ios_app_client_id)) .build();
Receiving Invites
Now that you're able to invite other users to your app, let's take a moment to focus on deep linking options. When you create your Intent
, you're able to add a URI
as a deep link. When a user receives your invite on Android, you can use Google Play Services and the AppInvite API to intercept this URI
and perform a custom action, such as presenting a welcome screen, for your new user.
boolean autodeeplink = true; mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(AppInvite.API) .enableAutoManage(this, this) .build(); AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, this, autodeeplink) .setResultCallback( new ResultCallback<AppInviteInvitationResult>() { @Override public void onResult(AppInviteInvitationResult result) { if (result.getStatus().isSuccess()) { //Get intent information Intent intent = result.getInvitationIntent(); String deepLink = AppInviteReferral.getDeepLink(intent); String invitationId = AppInviteReferral.getInvitationId(intent); } } } );
You'll notice that we created a boolean
named autodeeplink
. When this is set to true
, the Android system will automatically handle the received URI
through filters in your AndroidManifest.xml file. If it is set to false
, you can use the AppInvite API to extract information from the invitation and perform your custom action.
Conclusion
In this tutorial you have learned how to implement notifications from Firebase into your Android apps, and how to allow your users to easily share your app with their contacts. Understanding what's available in Firebase and how to implement the general features will go a long way in helping you quickly build apps that people enjoy using.
To learn more about Firebase or Android development in general, check out some of our other courses and tutorials here on Envato Tuts+.
Comments