Android Notifications – Tutorial | AndroidMonks

Android Notifications – Complete Tutorial

Notifications in android provides a way to interact with user outside the application. In Android the notification area is present when you swipe down from the Top. When you want to send out a notification to this area from your application (Either from a Activity or a Service), you will be following some general steps as given below.

Creating a Notification is pretty simple, however, it is important to create proper callbacks to link this Notification with the respective actions to be performed.

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.

Create a Notification – Basic Step

Make sure your Gradle has this dependency added

dependencies {
    implementation "com.android.support:support-compat:28.0.0"
}

Basic Notification

A notification in its most basic and compact form (also known as collapsed form) displays an icon, a title, and a small amount of content text. In this section, you’ll learn how to create a notification that the user can click on to launch an activity in your app.

Like we saw above, we need 3 basic things, an icon, a title, a small amount of content. We will be building these using a notification builder and then creating our notification. For this, we will need the NotificationCompat.Builder.

All it takes now is to add the required callbacks to the Builder and we have our first simple notification. Check out the code below.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.beglogo)
        .setContentTitle("Sample Notification")
        .setContentText("This is a one liner")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

This will create our Notification Builder. Once you are done creating your builder, we will let the OS know that there is a notification that has to be shown in the notification area, using the below code.

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(123, mBuilder.build());
second_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Intent Recieved"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textViewSample"
        android:onClick="NotificationStart"
        android:textColor="#556"/>
</LinearLayout>
SecondActivity.java
import android.app.Notification;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

TextView sampleTextView;

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

    }
    public void NotificationStart(View view)
    {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("AndroidMonks Sticker")
                .setTicker("AndroidMonks Sticker")
                .setContentText("Example")
                .setSmallIcon(R.drawable.ic_shape_1)
                .setOngoing(true);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(123, mBuilder.build());

    }
}

This will create our first simple Notification like below.

Simple notification
Simple notification

Setting a expandable Notification

How about create a notification which will expand to show more content. This is pretty simple, given you now know how to create a simple notification from above. You will additionally have to use the method setStyle() along with a object of BigStyleText(). See the below representation.

Reusing the above layout, but changing the class, we have. 

import android.app.Notification;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

TextView sampleTextView;

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

    }
    public void NotificationStart(View view)
    {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("AndroidMonks Sticker")
                .setTicker("AndroidMonks Sticker")
                .setContentText("Example")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Create a bigger line that expands, you can set any number of lines, but still it gets truncated after a certain point. Check the example here."))
                .setSmallIcon(R.drawable.ic_shape_1)
                .setOngoing(true);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(123, mBuilder.build());

    }
}
Expandable Notification
Expandable Notification

Responding to a Tap

Good job so far, but what happens when you click the Notifications you created above. Nothing! The Doc says, the purpose of the Notification is to land the user to some point inside the application. This way, there is a purpose for letting the user know about some action outside the application. In this section, we will see about responding to a tap.

We will be in need of a Pending Intent, holding the activity to be launched.

Check the below code to know how to launch a Activity from a notification.

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

TextView sampleTextView;
    PendingIntent pendingIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_layout);
        Intent intent = new Intent(this, MainActivity.class);

       pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    }
    public void NotificationStart(View view)
    {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("AndroidMonks Sticker")
                .setTicker("AndroidMonks Sticker")
                .setContentText("Example")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Create a bigger line that expands, you can set any number of lines, but still it gets truncated after a certain point. Check the example here."))
                .setSmallIcon(R.drawable.ic_shape_1)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setAutoCancel(true);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(123, mBuilder.build());

    }
}

I created a Simple Activity called MainActivity.java like below.

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button button;
    Boolean Toggle = false;

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

    }
}

My main_layout.xml looks like

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="60dp"
        android:textColor="@color/colorAccent"
        android:layout_gravity="center"
        android:id="@+id/serviceText"
        android:text="Launched from Notification"/>
</LinearLayout>

And Voila, we have our Application which gives the below output.

On clicking the Notification
On clicking the Notification

We get the below screen on clicking the notification.

Launched from notification
Launched from notification

Conclusion

This brings us to the end of creating simple Notifications. There are other cases of creating Tap actions like Replying from the Notification, or setting a button inside the notification. You can check all of them here.

Drop in any comments below.

“Learn and Be Curious”

Also Read  Spinner in Android - Implementation and Overview

Leave a Comment

Your email address will not be published. Required fields are marked *