Android Short Codes

Notification In Android

android notification
Written by Yasir Ameen

Notification notify Android user to keep informed about events. These events can be receiving an email, downloading a file,  receiving a text message and others. Notification shows on a status bar, you drag your finger down in order to see received notifications in notification drawer.

Following video demonstrates different types of notification.

 

Creating a Notification

Creating notification in Android is very easy. There are two commonly classes you will use for creating any types of notification.

  • NotificationCompact.Builder – we specify UI information and action for a notifications.
  • NotificationManager – class which handles how the persistent notification is to presented to the user.

 

Some of the types i showed here for give you basic understanding about the notification types.

Android Notification

 

Requirement For Creating Notification

For creating any type of notifications must contain the following –

  • Small Icon – set by calling setSmallIcon()
  • Title Text – set by calling setContentTitle()
  • Content Text – set by calling setContentText()

 

1) Creating Simple Notification

Simple notification only contain SmallIcon, TitleText and ContentText.

Button btn_simple = (Button) findViewById(R.id.btn_simno);
btn_simple.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        int notifyID = 1;
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.ic_announcement)
                        .setContentTitle("Android Notification")
                        .setContentText("This is simple notification without action.")
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

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

        //Issuing Notification
        mNotificationManager.notify(notifyID, mBuilder.build());


    }
});

android simple notification with small icon

2) Creating Notification With Pending Intent

Simple Notification does nothing for you, its just showed up on notification drawer. But if you want you notification to go somewhere or open an activity, you use Pending Intent. Following code snippet will show notification and when the user will click, it will open another activity.

Button btn_pInt = (Button) findViewById(R.id.btn_penInt);
btn_pInt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {


        int notifyID = 2;
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.ic_announcement)
                        .setContentTitle("New Recipe")
                        .setContentText("Check our new recipe with other stuff.")
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));


        //These lines will handle newly start activity with artificial back stack
        Intent resultIntent = new Intent(MainActivity.this, DetailsActivity.class);
        TaskStackBuilder stackBuilder =  TaskStackBuilder.create(MainActivity.this);
        stackBuilder.addParentStack(DetailsActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent pendingIntent =  stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);

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

        mBuilder.setAutoCancel(true);
        mNotificationManager.notify(notifyID,mBuilder.build());


    }
});

notification with pending intent


3) Creating Notification With Color

Applying color to the notification is very easy. Just simply call setColor() NotificationCompat.Builder() object and you are done.

Button btn_ncol = (Button) findViewById(R.id.btn_ncolor);
btn_ncol.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        int notifyID = 3;
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.ic_announcement)
                        .setContentTitle("New Recipe")
                        .setContentText("Check our new recipe with other stuff.")
                        .setColor(Color.parseColor("#009688"))
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

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

        mBuilder.setAutoCancel(true);
        mNotificationManager.notify(notifyID,mBuilder.build());


    }
});

notification with color

 

 

4) Creating Expandable Notification

If you want to show your notification much like an inbox and behave like a Expanded Layout then use NotificationCompat.InboxStyle in your notification. Set setBigContentTitle() method for the title text of expanded notification and use addLine() method to show adding tasks/emails/messages as your inbox content.

Button btn_expand = (Button) findViewById(R.id.btn_expandable);
btn_expand.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        int notifyID = 4;
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.ic_assignment)
                        .setContentTitle("Changes In Courses")
                        .setContentText("New Courses Added")
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        //String[] events = new String[6];
        inboxStyle.setBigContentTitle("New Courses Added:");

        String[] events = new String[5];
        events[0] = "Image Processing";
        events[1] = "Mathematical Sciences";
        events[2] = "Artificial Intelligence";
        events[3] = "Quantum Computing";
        events[4] = "Analytical Physics";

        for (int i = 0; i < events.length; i++) {
          inboxStyle.addLine(events[i]);
        }

        mBuilder.setStyle(inboxStyle);

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(notifyID, mBuilder.build());

    }
})

Screenshot_20160423-232025

 

 

5) Creating  Notification With Large Icon

Large Icon gives more meaning to the notification by showing customize icon. We can use app-launcher icon as a Large Icon so the user can recognize notifications. Simply call setLargeIcon() method of the NotificationCompat.Builder() object.

Button btn_licon = (Button) findViewById(R.id.btn_largeicon);
btn_licon.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        int notifyID = 0;
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.ic_announcement)
                        .setContentTitle("Android Notification")
                        .setContentText("New thread is started on Android Notification.")
                        .setColor(Color.parseColor("#03A9F4"))
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.reddit))
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

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

        mBuilder.setAutoCancel(true);
        mNotificationManager.notify(notifyID,mBuilder.build());

    }
});

Screenshot_20160423-232055

 

 

6) Creating  Heads-up Notification.

Android 5.0 includes Heads-up Notification, notification can appear floating in a small window. Heads-up notification is also a compact style notification you saw above. Its similar to whatsapp notification which appear in a floating small layout at top of the screen.

You can trigger Heads-up notification by two possibilities.

  • The user’s using full screen activity and you set setfullscreenIntent()
  • You specify the priority of your notification to HIGH and you use ringtones or vibrations

Following code snippet will Issue Heads-up Notification.

Button btn_nheads = (Button) findViewById(R.id.btn_nheads);
btn_nheads.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        int notifyID = 6;
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.ic_announcement)
                        .setContentTitle("Heads-up Notification")
                        .setContentText("Android notification system in lollipop.")
                        .setColor(Color.parseColor("#03A9F4"))
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setVibrate(new long[] { 100, 200, 300 })
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

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

        mBuilder.setAutoCancel(true);
        mNotificationManager.notify(notifyID,mBuilder.build());
    }
})

 

7) Creating  Notification With Actions.

You can implements actions to your notification and use PendingIntent to make them use. According to the documentation, you only specify direct actions to your notification which help you take decision easily.

You specify actions to your notification by calling addAction() method of the NotificationCompat.Builder() object.

addAction() method has two overload method, one of them you can use with PendingIntent object.

  • icon – you specify the drawable icon.
  • CharSequence – you specify the name of action.
  • PendingIntent – you specify what action should be taken.

Following code snippet will demonstrate Notification with Pending Intent.

Button btn_naction = (Button) findViewById(R.id.btn_naction);
btn_naction.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {


                int notifyID = 5;
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(MainActivity.this)
                                .setSmallIcon(R.drawable.ic_textsms_white_24dp)
                                .setContentTitle("Yasir Ameen")
                                .setContentText("Hey! check out my new post Android Notifications...")
                                .setColor(Color.parseColor("#009688"))
                                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.me))
                                .addAction(R.drawable.ic_close_white_24dp,"DISMISS",null)
                                .addAction(R.drawable.ic_reply_white_24dp,"REPLY",null)
                                .setPriority(NotificationCompat.PRIORITY_HIGH)
                                .setVibrate(new long[] { 100, 200, 300 })
                                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));


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

                mBuilder.setAutoCancel(true);
                mNotificationManager.notify(notifyID,mBuilder.build());
    }
}

Screenshot_20160423-232120

 

 

8) Creating  BigText Style Notification.

Some of the times we want show long information in notification and give our users to read bigtext such description of movies and events. we use NotificationCompat.BigTextStyle() object to specify Big Text by calling bigText() method and pass NotificationCompat.BigTextStyle() object to setStyle() method which is the NotificationCompat.Builder() object.

Button btn_bigtxt = (Button) findViewById(R.id.btn_bigtext);
btn_bigtxt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        int notifyID = 10;
        NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
                .setSmallIcon(R.drawable.ic_assignment)
                .setContentTitle("Yasir Ameen")
                .setContentText("Birthday Celebration!")
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.me))
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

        NotificationCompat.BigTextStyle btxt = new NotificationCompat.BigTextStyle()
                .bigText("Hey! I have a present for you on your birthday. We are going to dinner tonight, be ready i will pick you.");
        builder.setStyle(btxt);

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

        builder.setAutoCancel(true);
        mNotificationManager.notify(notifyID,builder.build());


    }
});

Screenshot_20160423-232248

 

9) Creating  BigPicture Style Notification.

Notification with Big Picture gives more meaning to the user about any events. You can add action such as share. We use NotificationCompat.BigPictureStyle() object to specify Big Picture by calling bigPicture() method and pass NotificationCompat.BigPictureStyle() object to setStyle() method which is the NotificationCompat.Builder() object.

Button btn_bigpic = (Button) findViewById(R.id.btn_bigpic);
btn_bigpic.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        int notifyID = 9;
        NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
                .setSmallIcon(R.drawable.ic_announcement)
                .setContentTitle("Picture Received")
                .setContentText("Touch to view your picture")
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));


            NotificationCompat.BigPictureStyle bpic = new NotificationCompat.BigPictureStyle()
                    .bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.big_android))
                    .setSummaryText("He is feeling alone, looking for someone.");

                builder.setStyle(bpic);

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

        builder.setAutoCancel(true);
        mNotificationManager.notify(notifyID,builder.build());


    }
});

Screenshot_20160423-232315

 

Congrats : You are now able to create useful notifications.
In my next part of this tutorial will be on download a file with notification progress.

you can learn more about notification here andrid developer site

 

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

4 Comments

Leave a Comment