Firebase Cloud Messaging for Android: Sending Push Notifications

In this Firebase Cloud Messaging tutorial, you will learn how to add push notifications to Drink-It, an app that reminds you to drink water through the day. By Evana Margain Puig.

4.8 (21) · 1 Review

Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Sending a Payload in the Notification

You have one last step to implement. If you close the app completely and send the notification, you’ll get it in the System UI. However, if you click it, the text on the screen is still Drink It and not the text of the notification.

To fix this, you need to modify the code in MyFirebaseMessagingService.kt. In handler.post, change the code in remoteMessage.notification to the following:

remoteMessage.notification?.let {
  val intent = Intent("MyData")
  intent.putExtra("message", remoteMessage.data["text"]);
  broadcaster?.sendBroadcast(intent);
}

This takes the information that comes in the payload of the notification with the key text and puts it in an intent called MyData with another key called message, which is directed to MainActivity.

To receive this, add this code to the onCreate() of your MainActivity:

val bundle = intent.extras
if (bundle != null) { 
  text_view_notification.text = bundle.getString("text")
}

With this, you’re displaying the content of the notification payload in text_view_notification.

Now, test that this works. Create a notification in Firebase Notification Composer as you did in the previous steps. This time, however, use the following configuration options in step 5 of the wizard.

Extra options for notification in Firebase console

In the key field, enter text. Then, in the value textfield, enter I know you haven’t finished your water bottle!.

Build and run, then send this notification and voila! Everything works now.

Test it in background and foreground and make sure the text view changes with the message received. This is how the app should look now:

Final result of the app with the notification data payload in the screen text view

Congratulations! You just created an Android app that reminds you to drink water. Just remember to schedule your notifications in Firebase Composer so they arrive regularly. Don’t forget to keep hydrated. :]

Where to Go From Here?

Download the completed project files by using the Download Materials button at the top or bottom of the tutorial.

If you want to learn more about Firebase for Android, check out our tutorial on Real-Time Databases or our tutorial on Authentication with Firebase.

We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!