Direct Reply Notification in Android like WhatsApp Tutorial

Hey guys, here is another useful tutorial. Today we will learn about Direct Reply Notification in Android. You might have seen this feature already in the very popular messaging app WhatsApp. Now we can directly reply to WhatsApp messages without even opening WhatsApp.

So if you are searching how you can implement this feature in your Android Project then, this is what we will be learning in this tutorial. So let’s begin.

Creating a new Android Studio Project

As always let’s do this thing in a new Android Studio Project. So for my Direct Reply Notifications I’ve already created a project named DirectReplyNotification.

Creating Interface

Here we have nothing much to do. We will create only a simple button and pressing that button will create a notification. As this post is only for an example so we are not going to cover about push notifications here. We will only see how Direct Reply Notification works.  If you want to learn about push notification you can check Firebase Cloud Messaging Tutorial here.

  • So come inside activity_main.xml and create a button here.



    

  • The above xml will generate the following design.
Direct Reply Notification Example

Direct Reply Notification Example

Defining Constants

  • For this project we need some constants values, like CHANNEL_ID, CHANNEL_NAME etc. So, first define all the Constant values inside MainActivity.java.
public class MainActivity extends AppCompatActivity {

    public static final String NOTIFICATION_REPLY = "NotificationReply";
    public static final String CHANNNEL_ID = "SimplifiedCodingChannel";
    public static final String CHANNEL_NAME = "SimplifiedCodingChannel";
    public static final String CHANNEL_DESC = "This is a channel for Simplified Coding Notifications";

    public static final String KEY_INTENT_MORE = "keyintentmore";
    public static final String KEY_INTENT_HELP = "keyintenthelp";

    public static final int REQUEST_CODE_MORE = 100;
    public static final int REQUEST_CODE_HELP = 101;
    public static final int NOTIFICATION_ID = 200;

Creating Notification Channel

  • So, from Android Nougat, creating a notification channel is compulsory for displaying notifications. Inside onCreate(), we will check if the device version is Android N or greater we will create a notification channel.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNNEL_ID, CHANNEL_NAME, importance);
            mChannel.setDescription(CHANNEL_DESC);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        }

Adding Click Listener to Button

  • Now, we will attach an OnClickListener to the Button. So inside onCreate() write the following lines of code.
findViewById(R.id.buttonCreateNotification).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayNotification();
            }
        });

  • Inside onClick() we are firing a method named displayNotification(). So we need to define this method inside MainActivity.
public void displayNotification() {

    }

  • Inside this method, we will build the notification.

Building Direct Reply Notification

  • Now lets define the displayNotification() method to display our Direct Reply Notification.
public void displayNotification() {

        //Pending intent for a notification button named More
        PendingIntent morePendingIntent = PendingIntent.getBroadcast(
                MainActivity.this,
                REQUEST_CODE_MORE,
                new Intent(MainActivity.this, NotificationReceiver.class)
                        .putExtra(KEY_INTENT_MORE, REQUEST_CODE_MORE),
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        //Pending intent for a notification button help
        PendingIntent helpPendingIntent = PendingIntent.getBroadcast(
                MainActivity.this,
                REQUEST_CODE_HELP,
                new Intent(MainActivity.this, NotificationReceiver.class)
                        .putExtra(KEY_INTENT_HELP, REQUEST_CODE_HELP),
                PendingIntent.FLAG_UPDATE_CURRENT
        );


        //We need this object for getting direct input from notification
        RemoteInput remoteInput = new RemoteInput.Builder(NOTIFICATION_REPLY)
                .setLabel("Please enter your name")
                .build();


        //For the remote input we need this action object
        NotificationCompat.Action action =
                new NotificationCompat.Action.Builder(android.R.drawable.ic_delete,
                        "Reply Now...", helpPendingIntent)
                        .addRemoteInput(remoteInput)
                        .build();

        //Creating the notifiction builder object 
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_email)
                .setContentTitle("Hey this is Simplified Coding...")
                .setContentText("Please share your name with us")
                .setAutoCancel(true)
                .setContentIntent(helpPendingIntent)
                .addAction(action)
                .addAction(android.R.drawable.ic_menu_compass, "More", morePendingIntent)
                .addAction(android.R.drawable.ic_menu_directions, "Help", helpPendingIntent);

        
        //finally displaying the notification
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

  • Right now you will see error on NotificationReceiver.class, as we haven’t created it yet.

Creating a Notification Action Handler

Now, finally we need to handle the input, and other buttons in the notification. For this we will create a Broadcast Receiver.

  • Create a class named NotificationReceiver and write the following code.
package net.simplifiedlabs.directreplynotification;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.RemoteInput;
import android.widget.Toast;

/**
 * Created by Belal on 2/27/2018.
 */
public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //getting the remote input bundle from intent
        Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
        
        //if there is some input
        if (remoteInput != null) {
            
            //getting the input value
            CharSequence name = remoteInput.getCharSequence(MainActivity.NOTIFICATION_REPLY);

            //updating the notification with the input value
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, MainActivity.CHANNNEL_ID)
                    .setSmallIcon(android.R.drawable.ic_menu_info_details)
                    .setContentTitle("Hey Thanks, " + name);
            NotificationManager notificationManager = (NotificationManager) context.
                    getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(MainActivity.NOTIFICATION_ID, mBuilder.build());
        }

        //if help button is clicked
        if (intent.getIntExtra(MainActivity.KEY_INTENT_HELP, -1) == MainActivity.REQUEST_CODE_HELP) {
            Toast.makeText(context, "You Clicked Help", Toast.LENGTH_LONG).show();
        }

        //if more button is clicked 
        if (intent.getIntExtra(MainActivity.KEY_INTENT_MORE, -1) == MainActivity.REQUEST_CODE_MORE) {
            Toast.makeText(context, "You Clicked More", Toast.LENGTH_LONG).show();
        }
    }
}

  • We also need to define this receiver inside our AndroidManifest.xml file. So write the following xml code inside the tag.

Displaying Direct Reply Notification

  • Now, we have everything, and to display the notification, we just need to play the application and then hit on the Create Notification Button.
Android Direct Reply Notification

Android Direct Reply Notification

  • Bingo! it is working absolutely fine.

Download Source Code

Now, if you still having some issues, you can check my GitHub Repository for this project from the link given below.

So, that’s all for this Direct Reply Notification Example friends. If you are having any confusions regarding this tutorial, feel free to leave your comments. And if you think the post is helpful please SHARE it with your friends. Thank You 🙂

The post Direct Reply Notification in Android like WhatsApp Tutorial appeared first on Simplified Coding.

Powered by WPeMatico

Author: Pawan Kumar

Close Menu
%d bloggers like this:
Skip to toolbar