Direct reply is an Android feature that allows the user to enter text into a notification and send it to the app associated with that notification. This allows the user to reply to a message in the notification without launching an activity within the app. This chapter will build on the knowledge gained in the previous chapter to create an example app that uses this notification feature.
Creating the DirectReply Project
Select the New Project option from the welcome screen and, within the resulting new project dialog, choose the Empty Views Activity template before clicking on the Next button.
Enter DirectReply into the Name field and specify com.ebookfrenzy.directreply as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 33: Android 13 and the Language menu to Kotlin. Modify the project to support view binding using the steps outlined in section 18.8 Migrating a Project to View Binding.
Designing the User Interface
Load the activity_main.xml layout file into the layout tool. With Autoconnect enabled, add a Button object beneath the existing “Hello World!” label, as shown in Figure 78-1. With the Button widget selected in the layout, use the Attributes tool window to set the onClick property to call a method named sendNotification. Use the Infer Constraints button to add any missing constraints to the layout if necessary. Before continuing, select the “Hello World!” TextView, change the id attribute to textView, and modify the text on the button to read “Notify”:
Requesting Notification Permission
Within the Project tool window, locate and double-click on the AndroidManifest.xml file to load it into the editor and modify the XML to add the permission element:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ebookfrenzy.audioapp" >
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
.
.
Code language: HTML, XML (xml)
Edit the MainActivity.kt file and begin by adding some additional import directives and a constant to act as request identification codes for the permission being requested:
.
.
import android.Manifest
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
.
.
class MainActivity : AppCompatActivity() {
.
.
private val NOTIFICATION_REQUEST_CODE = 101
.
.
Code language: Kotlin (kotlin)
Next, a method needs to be added to the class, the purpose of which is to take as arguments the permission to be requested and the corresponding request identification code. Remaining with the MainActivity.kt class file, implement this method as follows:
private fun requestPermission(permissionType: String, requestCode: Int) {
val permission = ContextCompat.checkSelfPermission(this,
permissionType)
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(permissionType), requestCode
)
}
}
Code language: Kotlin (kotlin)
When the request has been handled, the onRequestPermissionsResult() method will be called on the activity, passing through the identification code and the request results. The next step, therefore, is to implement this method within the MainActivity.kt file as follows:
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
NOTIFICATION_REQUEST_CODE -> {
if (grantResults.isEmpty() || grantResults[0]
!= PackageManager.PERMISSION_GRANTED
) {
Toast.makeText(
this,
"Notification permission required",
Toast.LENGTH_LONG
).show()
}
}
}
}
Code language: Kotlin (kotlin)
Before testing the app, all that remains is to call the newly added requestPermission() method when the app launches. Remaining in the MainActivity.kt file, modify the onCreate() method as follows:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
requestPermission(Manifest.permission.POST_NOTIFICATIONS,
NOTIFICATION_REQUEST_CODE)
}
Code language: Kotlin (kotlin)
Creating the Notification Channel
As with the example in the previous chapter, a channel must be created before a notification can be sent. Edit the MainActivity.kt file and add code to create a new channel as follows:
import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.graphics.Color . . class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val NOTIFICATION_REQUEST_CODE = 101
Code language: Kotlin (kotlin)
Building the RemoteInput Object
The key element that makes direct reply in-line text possible within a notification is the RemoteInput class. The previous chapters introduced the PendingIntent class and explained how it allows one application to create an intent and then grant other applications or services the ability to launch that intent from outside the original app. In that chapter, entitled An Android Studio Notifications Tutorial, a pending intent was created that allowed an activity in the original app to be launched from within a notification. The RemoteInput class allows a request for user input to be included in the PendingIntent object along with the intent. When the intent within the PendingIntent object is triggered, for example, launching an activity, that activity is also passed any input provided by the user.
The first step in implementing a direct reply within a notification is to create the RemoteInput object. This is achieved using the RemoteInput.Builder() method. To build a RemoteInput object, a key string is required that will be used to extract the input from the resulting intent. The object also needs a label string that will appear within the text input field of the notification. Edit the MainActivity.kt file and add the sendNotification() method. Note also the addition of some import directives and variables that will be used later as the chapter progresses:
package com.ebookfrenzy.directreply
.
.
import android.content.Intent
import android.app.RemoteInput
import android.view.View
import android.app.PendingIntent
class MainActivity : AppCompatActivity() {
private val notificationId = 101
private val KEY_TEXT_REPLY = "key_text_reply"
.
.
fun sendNotification(view: View) {
val replyLabel = "Enter your reply here"
val remoteInput = RemoteInput.Builder(KEY_TEXT_REPLY)
.setLabel(replyLabel)
.build()
}
.
.
}
Code language: Kotlin (kotlin)
Now that the RemoteInput object has been created and initialized with a key and a label string, it will need to be placed inside a notification action object. Before that step can be performed, however, the PendingIntent instance needs to be created.
Creating the PendingIntent
The steps to creating the PendingIntent are the same as those outlined in the An Android Studio Notifications Tutorial chapter, except that the intent will be configured to launch MainActivity. Remaining within the MainActivity.kt file, add the code to create the PendingIntent as follows:
fun sendNotification(view: View) {
.
.
val resultIntent = Intent(this, MainActivity::class.java)
val resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_MUTABLE
)
}
Code language: Kotlin (kotlin)
Creating the Reply Action
The in-line reply will be accessible within the notification via an action button. This action needs to be created and configured with an icon, a label to appear on the button, the PendingIntent object, and the RemoteInput object. Modify the sendNotification() method to add the code to create this action:
.
.
import android.graphics.drawable.Icon
import android.app.Notification
.
.
fun sendNotification(view: View) {
.
.
val icon = Icon.createWithResource(this@MainActivity,
android.R.drawable.ic_dialog_info)
val replyAction = Notification.Action.Builder(
icon,
"Reply", resultPendingIntent)
.addRemoteInput(remoteInput)
.build()
}
.
.
Code language: Kotlin (kotlin)
At this stage in the tutorial, we have the RemoteInput, PendingIntent, and Notification Action objects built and ready to be used. The next stage is to build the notification and issue it:
.
.
import com.google.android.material.R.color
.
.
fun sendNotification(view: View) {
.
.
val newMessageNotification = Notification.Builder(this, channelID)
.setColor(ContextCompat.getColor(this,
color.design_default_color_primary))
.setSmallIcon(
android.R.drawable.ic_dialog_info)
.setContentTitle("My Notification")
.setContentText("This is a test message")
.addAction(replyAction).build()
val notificationManager = getSystemService(
Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(notificationId,
newMessageNotification)
}
Code language: Kotlin (kotlin)
With the changes made, compile and run the app, allow notifications, and test that tapping the button issues the notification successfully. When viewing the notification drawer, the notification should appear as shown in Figure 78-2:
Tap the Reply action button so that the text input field appears, displaying the reply label embedded into the RemoteInput object when it was created.
Enter some text and tap the send arrow button at the end of the input field.
Receiving Direct Reply Input
Now that the notification is successfully seeking input from the user, the app needs to do something with that input. This tutorial’s objective is to have the text entered by the user into the notification appear on the TextView widget in the activity user interface.
When the user enters text and taps the send button, the MainActivity is launched via the intent in the PendingIntent object. Embedded in this intent is the text entered by the user via the notification. Within the onCreate() method of the activity, a call to the getIntent() method will return a copy of the intent that launched the activity. Passing this through to the RemoteInput.getResultsFromIntent() method will, in turn, return a Bundle object containing the reply text, which can be extracted and assigned to the TextView widget. This results in a modified onCreate() method within the MainActivity.kt file, which reads as follows:
.
.
override fun onCreate(savedInstanceState: Bundle?) {
.
.
handleIntent()
}
private fun handleIntent() {
val intent = this.intent
val remoteInput = RemoteInput.getResultsFromIntent(intent)
if (remoteInput != null) {
val inputString = remoteInput.getCharSequence(
KEY_TEXT_REPLY).toString()
binding.textView.text = inputString
}
}
.
.
Code language: Kotlin (kotlin)
After making these code changes build and run the app once again. Click the button to issue the notification and enter and send some text from within the notification panel. Note that the TextView widget in the MainActivity is updated to display the in-line text that was entered.
Updating the Notification
After sending the reply within the notification, you may have noticed that the progress indicator continues to spin within the notification panel, as highlighted in Figure 78-4:
The notification shows this indicator because it is waiting for a response from the activity confirming receipt of the sent text. The recommended approach to performing this task is to update the notification with a new message indicating that the reply has been received and handled. Since the original notification was assigned an ID when it was issued, it can be used again to perform an update. Add the following code to the handleIntent() method to perform this task:
private fun handleIntent() {
.
.
if (remoteInput != null) {
val inputString = remoteInput.getCharSequence(
KEY_TEXT_REPLY).toString()
binding.textView.text = inputString
val repliedNotification = Notification.Builder(this, channelID)
.setSmallIcon(
android.R.drawable.ic_dialog_info)
.setContentText("Reply received")
.build()
notificationManager?.notify(notificationId,
repliedNotification)
}
}
Code language: Kotlin (kotlin)
Test the app one last time and verify that the progress indicator goes away after the in-line reply text has been sent and that a new panel appears, indicating that the reply has been received:
Summary
The direct reply notification feature allows text to be entered by the user within a notification and passed via an intent to an activity of the corresponding application. Direct reply is made possible by the RemoteInput class, an instance of which can be embedded within an action and bundled with the notification. When working with direct reply notifications, it is important to let the NotificationManager service know that the reply has been received and processed. The best way to achieve this is to update the notification message using the notification ID provided when the notification was first issued.