Home » Android » Android Core » Android Notification with Sound and Icon Tutorial

About Mike Dalisay

Mike Dalisay

Android Notification with Sound and Icon Tutorial

My app needed a simple Android notification with sound and icon. So here’s the code I used to make that happen. I know that there are many other types of notification in Android, but this time, I just want to show you a very simple code that can be a solution to your problem too!

I will probably create a series of blog posts regarding Android notifications, and make it like a cheat sheet for all of us. Anyway, here are some screenshots of today’s code output:
 
 
 
 

1-android-notification-tutorial
When you run this code.

 

2-android-notification-sound
When you click the button “Show Notification”,
the notification bar will have the ninja icon
and you will hear a sound
(make sure you’re not in silent mode).

 

3-android-notification-icon
When you slide down the notification bar.

Hide Notification

How to hide the notification? There are two ways:

1. First, you can click the “Cancel Notification” button.

2. Or, second, swipe the notification to left or right (swipe the notification in the third image).

These ways were set programatically, so read the code (with comments) below.

Let’s Code!

Here’s are our awesome code: MainActivity.java

package com.example.androidnotificationbar;

import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // listener handler
        View.OnClickListener handler = new View.OnClickListener(){
            public void onClick(View v) {

                switch (v.getId()) {

                    case R.id.btnShowNotification:
                        showNotification();
                        break;

                    case R.id.btnCancelNotification:
                        cancelNotification(0);
                        break;
                }
            }
        };

        // we will set the listeners
        findViewById(R.id.btnShowNotification).setOnClickListener(handler);
        findViewById(R.id.btnCancelNotification).setOnClickListener(handler);

    }

    public void showNotification(){

        // define sound URI, the sound to be played when there's a notification
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // intent triggered, you can add other intent for other actions
        Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
        PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

        // this is it, we'll build the notification!
        // in the addAction method, if you don't want any icon, just set the first param to 0
        Notification mNotification = new Notification.Builder(this)

            .setContentTitle("New Post!")
            .setContentText("Here's an awesome update for you!")
            .setSmallIcon(R.drawable.ninja)
            .setContentIntent(pIntent)
            .setSound(soundUri)

            .addAction(R.drawable.ninja, "View", pIntent)
            .addAction(0, "Remind", pIntent)

            .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // If you want to hide the notification after it was selected, do the code below
        // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, mNotification);
    }

    public void cancelNotification(int notificationId){

        if (Context.NOTIFICATION_SERVICE!=null) {
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
            nMgr.cancel(notificationId);
        }
    }

}

I also put the ninja icon in our drawable folder, that’s the source of our icon.

Please share what Android notification example you want next!

 

(0 rating, 0 votes)
You need to be a registered member to rate this.
23 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

23 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Pablo ungaro
Pablo ungaro
7 years ago

Post one example for c2dm please

Mike Dalisay
7 years ago

Hi guys, for those having problems with the code download, see my original post for the fixed download link http://www.codeofaninja.com/2013/08/android-notification-bar-sound-icon.html

ThemeBowl
6 years ago

Hi,Thanks for sharing this tutorial.I would like to know how to show notification on an app after 2 days since its use?

dhara
dhara
6 years ago

do u have to set any permission in the manifest.xml file???plz reply

ashish
ashish
6 years ago

Hi thanks but I want to show notification after every 24 hours automatically how do I do this please help

Bishal
Bishal
5 years ago
Reply to  ashish

Use AlarmManager by using instance of calender.

Anuj
Anuj
6 years ago

I am creating this Notification in a Fragment and is showing an error while calling constructor of intent.

The constructor Intent(QuoteFragment, Class) is undefined

fda
fda
6 years ago

I cannot access your source code link.

Byron Kiourtzoglou
6 years ago

Hello all,

We have fixed the download link, sorry for the inconvenience.

Best regards
Byron

noidf
noidf
6 years ago

Thank you

Kim
Kim
6 years ago

I just want to ask what is the purpose of the menu.xml?

Shenzhen
Shenzhen
6 years ago

Great tutorial. I downloaded the source code and it worked nice. At the moment I copied the NotificationReceiver.class in my project but pintent doesn’t work. The second activity doesn’t start. Do you got an idea what could be the reason?

shivpal
shivpal
6 years ago

hi i want notification like whats app in my android app for sending request like leave and approve from other side how can i do this please help i need it badly.

ashDyeena
ashDyeena
5 years ago

hye.. how to create notification bar to notify the others devices connect to our wifi hotspot?
can you help me?

new bee
new bee
5 years ago

Hi. i want the notification should be on app icon. fine if it is coming in bar, but i want on app icon as well. can you please help me out?

Jonathan
Jonathan
5 years ago

Any advice on how i can receive push notification even when the application is “not running”?

Mohammad
Mohammad
5 years ago

Thanks

Tushar
Tushar
4 years ago

hello.code is running perfectly without any error but icon on notification is not displaying.it is set to automatically android icon.i m changing it with setsmallicon(r.drawable.myicon).still it is not changing icon.

sitwell
sitwell
4 years ago

Thanks for the codes. It worked fine for me.

sachi
sachi
2 years ago

Error at NotificationReceiver

Mehran
Mehran
11 months ago

Hi , please update the download link , i couldn’t download that

Nataly Evagorou
Editor
11 months ago
Reply to  Mehran

Hello, it seems that the original source removed this .zip file https://www.androidcode.ninja/android-notification-bar-sound-icon/