Main navigation

Android Notification Example with Progress bar, Big Picture and Direct Reply

adsense

Download full code here:

Android Notification Example

What is Notification in Android

An android notification is a message that a developer can display to the user outside of application’s normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. On clicking notification, a new Activity is opened displaying details of android notification.

How to make Progress Bar in Android Notification

This notification generally appears whenever we download a particular image, song, video or any other file from internet. It display progress of download with a progress bar that appears as notification in Android.

How to make Big Picture Style in Android Notification

Bigpicturestyle notification appears in different News and E-Commerce websites. Here large-format notifications that include a large image attachment is appeared as notification in android.

How to make Direct Reply in Android Notification

This is new feature included in Notifications in Android N (Android Version 7.0). It is new MessagingStyle in android where user can directly write in notification and reply to other user.

Let’s start making these types of Android Notification Example. We hope you will enjoy it.:)

Creating a New Project – Android Notifications Example

  1. Open Android Studio and create a new project Android Speech to Text Tutorial and company domain application.example.com (We have used our own company domain i.e androidtutorialpoint.com. Similarly you can use yours).
  2. Click Next and choose Min SDK (It should be maximum possible). Again Click Next and Choose Blank Activity .
  3. Choose the Activity as MainActivity and click next.
  4. Leave all other things as default and Click Finish.

A new project will be created and gradle will resolve all the dependencies. Make Sure you build.gradle has following dependency to support latest Android Version.

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.androidtutorialpoint.androidnotificationsexample"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    testCompile 'junit:junit:4.12'
}

Now let’s make Layout of our Android Notification Example. Make following changes in activity_main.xml:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.androidtutorialpoint.androidnotificationsexample.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_dark"
        android:textColor="#fff"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="50dp"
        android:text="Show Text Notification" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_dark"
        android:textColor="#fff"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_margin="50dp"
        android:text="Show Loading Notification" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_dark"
        android:textColor="#fff"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_margin="50dp"
        android:text="Show Reply Notification" />

</RelativeLayout>

In the above code we have created three buttons each for showing notifications of Progressive Bar, Big Picture and Direct Reply.

Also make another layout file named activity_notification.xml at same path (…/AndroidNotificationsExample/app/src/main/res/layout/activity_notification.xml). This file will be utilized for showing second activity which will be called when someone clicks on any notification.

activity_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
                xmlns:tools="https://schemas.android.com/tools"
                android:id="@+id/activity_notification"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context="com.androidtutorialpoint.androidnotificationsexample.ResultActivity">

    <TextView
        android:id="@+id/replyMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text=""
        android:textSize="15sp"
        android:textColor="#000" />
</RelativeLayout>

In this tutorial, we will use two activities, First is ofcourse MainActivity and second is ResultActivity. ResultActivity is called whenever a user clicks on notification. We have to register this second Activity, so make following changes in AndroidManifest.xml:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.androidtutorialpoint.androidnotificationsexample"
          xmlns:android="https://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".ResultActivity"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>

</manifest>

In the above code, support for Android 4.0.3 and earlier is added by specifying the parent of the Activity by adding a element as the child of the .
For this element, set android:name=”android.support.PARENT_ACTIVITY”. Set android:value=”.

Also support for Android 4.1 and later, android:parentActivityName attribute is added to the element of the ResultActivity.

Now we will include main functionality in our code. We will divide it into three parts according to each of three Android Notification Example. We will setOnClickListener for each of the button in MainActivity.

Support for Progress Bar in Android Notification

Add following code in onCreate() method of MainActivity.

Code of Progress Bar in Android Notification

        Button b2 = (Button) findViewById(R.id.button2);
        b2.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                // Creates an explicit intent for an Activity in your app
                Intent resultIntent = new Intent(MainActivity.this, ResultActivity.class);

                TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);

                stackBuilder.addParentStack(ResultActivity.class);

                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent =
                        stackBuilder.getPendingIntent(
                                0,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(MainActivity.this)
                                .setSmallIcon(R.drawable.notification_icon)
                                .setContentTitle("Downloading Resource");

                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mBuilder.setProgress(0, 0, true);
                mNotificationManager.notify(1, mBuilder.build());
            }
        });

In the above code, First of all we have created an Intent to start Activity. Then stack builder is created by calling TaskStackBuilder.create(). TaskStackBuilder is used to go back to the previous activity after clicking on notification. For Example: When you click on a notification then a new Activity appears (In our case ResultActivity). Now if you want to go back to the previous Activity (In our case MainActivity) then Stack Builder will be used.

In an android Notification, action is defined by a PendingIntent containing an Intent that starts an Activity in application. To associate the PendingIntent with a gesture, we have called NotificationCompat.Builder. Also to start an Activity when the user clicks the notification text in the notification drawer, we have added the PendingIntent by calling setContentIntent().

Android Notification is created through NotificationCompat.Builder.build(), which returns a Notification object containing our specifications. In our case returned object is mBuilder. To issue the notification, we passed the Notification object to the system by calling NotificationManager.notify().

The major point here is mBuilder.setProgress(0,0,true). To display an indeterminate activity indicator, we have added it in our notification with setProgress(0, 0, true) (the first two arguments are ignored). So here a progress bar will be shown in notification just like shown in an actual download. Progress Bar Notification will look as follows:

Android Notification ExampleProgress Bar

So our code for Progress bar in Android notification is complete. Now let’s develop second android notification example i.e. BigPictureStyle. This will be an android notification with image example.

Support for Big Picture Notification Android

In this android notification example, we will create a notification just like you see in Amazon or some news app. There will be a large image shown in notification. This will be created on clicking Button1.

Code of Big image in Notification Android

Button b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                // Creates an explicit intent for an Activity in your app
                Intent resultIntent = new Intent(MainActivity.this, ResultActivity.class);

                TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);

                stackBuilder.addParentStack(ResultActivity.class);

                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent =
                        stackBuilder.getPendingIntent(
                                0,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(MainActivity.this)
                                .setSmallIcon(R.drawable.notification_icon)
                                .setContentTitle("Android Tutorial Point is Best");

                Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.sales);
                NotificationCompat.BigPictureStyle s = new NotificationCompat.BigPictureStyle().bigPicture(largeIcon);
                s.setSummaryText("Summary text appears on expanding the notification");
                mBuilder.setStyle(s);

                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, mBuilder.build());
            }
        });

Above code is pretty much self explanatory in line with progress bar code. There is one crucial difference as compared to ProgressBar and that is addition of BigPictureStyle. Notification.BigPictureStyle is a helper class for generating large-format notifications that include a large image attachment. It only accepts images in the form of bitmap so we casted drawable resource into Bitmap. Following image shows how it will look like:

Android Notification ExampleBigPicture Notification

Now comes the final example of Android Notification which is direct reply.

Enhanced Notifications in Android N with Direct Reply

Starting in Android 7.0 (API level 24), users can respond directly to text messages or update task lists from within the notification dialog. On a handheld, the inline reply action appears as an additional button displayed in the notification.

Note: You can only use this feature in Android 7.0. So either run this particular example in a smartphone supporting Android 7.0 or run in an emulator.

Direct Reply notification will appear if you click on Button3. Add following code in MainActivity:

Code of Direct Reply in Android N Notification

Button b3 = (Button) findViewById(R.id.button3);
        b3.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                // Key for the string that's delivered in the action's intent.
                String replyLabel = "Reply Here";
                RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
                        .setLabel(replyLabel)
                        .build();

                // Creates an explicit intent for an Activity in your app
                Intent resultIntent = new Intent(MainActivity.this, ResultActivity.class);

                TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);

                stackBuilder.addParentStack(ResultActivity.class);

                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent =
                        stackBuilder.getPendingIntent(
                                0,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );
                // Create the reply action and add the remote input.

                // Add to your action, enabling Direct Reply for it
                NotificationCompat.Action action =
                        new NotificationCompat.Action.Builder(R.drawable.notification_icon, replyLabel, resultPendingIntent)
                                .addRemoteInput(remoteInput)
                                .setAllowGeneratedReplies(true)
                                .build();

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(MainActivity.this)
                                .addAction(action)
                                .setAutoCancel(true)
                                .setSmallIcon(R.drawable.notification_icon)
                                .setContentTitle("Android Tutorial Point Says")
                                .setContentText("Do you like my tutorials ?");

                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(mRequestCode, mBuilder.build());
            }
        });

In the above code, we have created an instance of RemoteInput.Builder. It adds a RemoteInput to a Notification.Action, sets the result key as quick_reply, and sets the label as Quick reply. Users are prompted to input a response when they trigger the action. The results are sent along with the intent and can be retrieved with the result key (provided to the RemoteInput.Builder constructor) from the Bundle returned by getResultsFromIntent(Intent).

Then we have attached the RemoteInput object to an action using addRemoteInput(). Finally this action is added to the notification through .addAction(action) in NotificationCompat.Builder. This is how direct reply is enabled in notification.

So our code MainActivity.java is complete. You can see full code of MainActivity here:

Full code of MainActivity

Now in the last step, we will create a second Activity named ResultActivity which will be called whenever a user clicks on notification. Also whenever a user write some reply in notification and click on “Reply” then it will appear as text in this Activity.

Create a new file named ResultActivity.java at the same path where MainActivity.java is located. Add following code:

ResultActivity.java

package com.androidtutorialpoint.androidnotificationsexample;

import android.app.NotificationManager;
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.support.v7.app.AppCompatActivity;
import android.widget.TextView;

/**
 * Created by navneet on 3/12/16.
 */

public class ResultActivity extends AppCompatActivity {

    // Key for the string that's delivered in the action's intent.
    private static final String KEY_TEXT_REPLY = "key_text_reply";

    // mRequestCode allows you to update the notification.
    int mRequestCode = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        TextView textView = (TextView) findViewById(R.id.replyMessage);
        textView.setText(getMessageText(getIntent()));

        String returnMessage = "Thank you";

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_stat_toggle_check_box)
                        .setContentText(returnMessage);

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //update notification
        mNotificationManager.notify(mRequestCode, mBuilder.build());
    }

    private CharSequence getMessageText(Intent intent) {
        Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
        if (remoteInput != null) {
            return remoteInput.getCharSequence(KEY_TEXT_REPLY);
        }
        return null;
    }
}

In the above code, we have called getResultsFromIntent() by passing the notification action’s intent as the input parameter. This method returns a Bundle that contains the text response. Then required text is written using textView.setText(getMessageText(getIntent()));. getMessageText will grab input from notification and return it. Finally notification is build and issued using same notification ID that we provided for the previous notification i.e mRequestCode.

So our code of Android Notification Example is complete. Run this code. Following screen will appear:

Android Notification Example

Now when you click on each button, different notifications will appear. For Example If you click on “Show Reply Notification” then following will appear where you can write any text:

Android Notification ExampleDirect Reply Notification

On clicking Reply following screen will appear showing the message which you write in notification:

Android Notification Example

You can see its demo in the YouTube video given at start of tutorial.




What’s Next ??

You can see our other tutorials on material design like Android ScrollView, ViewPager and Expandable ListView Tutorials etc.

We hope you liked our Android Notification Example, please leave comments in the comment section below in the case of any doubts. Let us know how do you liked this Android Notification Example.

To download the full code of Android Notification Example, Click on the Download Now link below.

Android Notification Example


Reader Interactions

Comments

  1. Very nice tutorials.. my one stop site for latest and cool stuff.
    please find a way to fix the downloads section. it’s not kind of cool to keep entering details if I want to download stuff, you may consider adding login section with sessions such that when a user is logged in he can automatically get the link or download

Leave a Reply

Advertisment ad adsense adlogger