Difference between revisions of "An Android 7 Firebase Remote Notification Tutorial"
(Created page with "<br><br> In the preceding chapter a new Firebase project was created and the appropriate steps taken to integrate Firebase into an Android Studio project. These steps were tak...") |
(No difference)
|
Revision as of 18:10, 27 June 2016
In the preceding chapter a new Firebase project was created and the appropriate steps taken to integrate Firebase into an Android Studio project. These steps were taken in preparation for the Firebase remote notification tutorial covered in this chapter.
This chapter will introduce the Notifications section of the Firebase console and explain how to send a message to a specific app. The app will then be modified to allow the receipt of notifications when the app is in the foreground and to support the inclusion of custom data within the Firebase notification.
Sending a Firebase Notification
Begin by launching the FirebaseNotify app created in the previous chapter on a physical Android device. Once the app is running, place it into the background by tapping the circular home button in the bottom status bar. By default notifications of this type are only delivered to apps that are either not running, or currently in the background.
Open a web browser and navigate to https://console.firebase.google.com/ to sign into your Firebase console and select the Firebase Notification Demo project created in the previous chapter. Once the project has loaded, select the Notifications option located in the left-hand panel of the console:
Figure 54-1
In the main panel, click on the button that reads Send Your First Message to display the message composition screen. Enter a text message into the Message text field and an optional message label (this is used to reference the notification within the Firebase system and is not seen by the app users) and leave the delivery date to Send Now.
In the target section, options are available to target different groups of app users. For the purposes of this example, the notification will target all users of the com.ebookfrenzy.firebasenotify app so make sure that User segment is selected before choosing the package name from the menu as demonstrated in Figure 54-2:
Figure 54-2
Note that the AND option may be used to add additional target criteria such as the version of the app, the spoken language of the user and whether the user has made a previous purchase within the app.
By default, the title of the notification will be set to the name of the corresponding app. The advanced settings section of the Firebase message composition screen allows this title to be changed. To access this setting, click on the Advanced options header in the message composition screen as highlighted in Figure 55-4 and enter the title string into the Title field:
Figure 54-3
With the notification message configured, click on the Send Message button, review the settings in the resulting panel and click on the Send button:
Reviewing a Firebase notification message
Figure 54-4
Receiving the Notification
After the message has been sent, return to the device on which the app is running and look for a notification indicator in the top status bar. Once the indicator appears, slide downward from the status bar to view the notification which will contain the message text entered when the notification was composed within the Firebase console:
Figure 54-5
Tapping the notification will launch the FirebaseNotify app.
Including Custom Data within the Notification
Firebase messaging also provides the option to pass key-value based data within the notification. This data can then be retrieved by the activity that is launched when the notification is selected on the device. The key-value data pairs to be included with the notification are specified from within the Advanced options section of the message composition screen. Figure 54-6, for example, shows two custom data pairs configured for a notification:
Figure 54-6
Within the activity launched when the user taps the notification on the device, the getIntent() method may be used to obtain a reference to the Intent object that triggered the launch. Calling the getExtras() method on that Intent will return a Bundle object containing the custom data.
The value associated with each key may be accessed by passing through the key value to getString() method of the Bundle object.
Edit the FirebaseNotifyActivity.java file and modify the onCreate() method to extract the value for a key of “MyKey1” and display that value on the myTextView widget in the activity user interface layout:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_firebase_notify); Bundle customData = getIntent().getExtras(); if (customData != null) { TextView textView = (TextView) findViewById(R.id.myTextView); textView.setText(customData.getString("MyKey1")); } }
Build and run the app on a physical Android device and place it into the background. Using the Firebase console, compose a new message targeted at the FirebaseNotify app. Before sending the notification, open the Advanced options panel and enter MyKey1 as the key and a string of your choice as the corresponding value. Send the message, refer to the device on which the app is running and pull down the notification shade when the notification icon appears in the status bar. Tap the notification to launch the activity and note that the string entered into the value field is now displayed on the TextView widget. Custom data has successfully been passed from the Firebase console via a notification to the main activity of the app.
Foreground App Notification Handling
As previously outlined an app will not, by default, receive a Firebase notification if it is currently the foreground app. In order for a foreground app to receive the notification, it must implement a service that extends FirebaseMessagingService class and override the onMessageReceived() method within that class.
With the FirebaseNotify project loaded into Android Studio, right-click on the app -> java -> com.ebookfrenzy.firebasenotify entry and select New -> Service -> Service from the menu. In the configuration dialog, name the class MyFBMessageService and enable both the Exported and Enabled options before clicking on the Finish button.
Edit the newly created MyFBMessageService.java file and modify it to extend the FirebaseMessagingService class, implement the onMessageReceived() method and remove the existing onBind() method:
package com.ebookfrenzy.firebasenotify; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFBMessageService extends FirebaseMessagingService { String TAG = "firebasenotify"; public MyFBMessageService() { } @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "Notification Title: " + remoteMessage.getNotification().getTitle()); Log.d(TAG, "Notification Message: " + remoteMessage.getNotification().getBody()); } }
When the onMessageReceived() method is called, it is passed as an argument a RemoteMessage object. Contained within this object is an instance of the RemoteMessage.Notification class. This object is used to contain the details of a Firebase remote notification.
In the above code, the getNotification() method of the RemoteMessage object is called to access the RemoteMessage.Notification object. The getTitle() method of the RemoteMessage.Notification object is then called to obtain the title text of the message while the getBody() method returns the notification body text. These strings are both displayed on the Android Studio console.
The final task before testing the code is to modify the service entry within the AndroidManifest.xml file to add an intent filter for the Firebase messaging event:
<service android:name=".MyFBMessageService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>
Once the changes have been made, build and run the app on a physical Android device and display the Android Monitor tool window so that the console output from the device is visible. Using the Firebase console, send a new notification to the app using the steps outlined earlier in the chapter. Once the notification has arrived on the device, output should appear in the Android Monitor tool window containing the message title and body text from the notification:
Figure 54-7
Summary
In addition to local notifications, Android also provides a way to send notifications remotely using the Firebase notifications system. Notifications can be targeted to users using a variety of categories including all users of an app, a particular spoken language, an app version or even to a specific Android device. This chapter has demonstrated how to send and receive remote notifications, including the implementation of a service to receive notifications for a foreground app and the passing of custom data to the app from the remote server.