Get $500+ of the best After Effects files, video templates and music for only $20!
Android SDK: Using Alerts, Toasts and Notifications

Android SDK: Using Alerts, Toasts and Notifications

Tutorial Details
  • Technology: Android SDK
  • Difficulty: Beginner
  • Completion Time: 10 - 15 Minutes

If you have an Android powered device, then you will already have experienced different types of notifications. They’re good for telling users about errors, warnings or informing them of completed tasks and it’s best to place them in a type of notification, such as an alert dialog, which allows you to communicate with users “outside” of user interfaces.

The Android SDK offers three main types of notifications – enough to cover all of your needs:

  • Alert Dialogs
  • Toasts
  • Notifications

In this tutorial, we will cover all three notification types.

Alert Dialogs

Creating alert dialogs is pretty straight-forward: you can construct an AlertDialog by using its Builder class, whose methods all return an instance of Builder, which basically means you can chain a series of method calls together. For example:

new AlertDialog.Builder(this).setTitle("Argh").setMessage("Watch out!").setNeutralButton("Close", null).show();
Android-SDK-Notifications

In the snippet above, you’re accessing AlertDialog’s static Builder class and handing it the context where the dialog will be displayed.

setNeutralButton(String, OnClickListener) creates a button with the specified title and OnClickListener to handle anything that should happen on a click. You can simply give it a value of null because AlertDialog buttons always close when clicked; your OnClickListener would simply handle additional, custom instructions.

Now you’re probably wondering why the word “neutral” is contained in that method name, right? You can create three types of buttons in total:

  1. setPositiveButton

    Describes an intended action or a confirmation, e.g. “Save” or “Yes”.

  2. setNeutralButton

    Describes a “neutral” action such as “Close”.

  3. setNegativeButton

    Describes a cancellation or simply a “No”.

It’s important to note that if you add all three of these buttons, they will be in the same order as the list above, so sometimes you might have to switch “neutral” and “negative” to achieve a desired order. So, the following snippet:

new AlertDialog.Builder(this).setTitle("Argh").setMessage("Watch out!").setNegativeButton("Cancel", null).setPositiveButton("OK", null).setNeutralButton("No", null).show();

Would produce this alert:

Android-SDK-Notifications

And always remember to create at least one button so your dialog can be closed, otherwise you’ll have frustrated users seeing this:

Android-SDK-Notifications

Finally, another popular method is setIcon(int resourceId). It should be self-explanatory:

new AlertDialog.Builder(this).setTitle("Argh").setMessage("Watch out!").setIcon(R.drawable.icon).setNeutralButton("Close", null).show();
Android-SDK-Notifications

Note: The most important methods have been covered here. For a full list of builder methods, visit the API Docs.

Toasts

Toasts are a great way to deliver unobtrusive status messages to users, because unlike Alert Dialogs they do not take focus away from the Activity. They’re perfect for displaying notifications that don’t need too much attention, for example to tell the user that a download has completed. As Toasts fade away automatically and are quite subtle in their nature, it may not be guaranteed that a user will have taken full notice of it. So in plain English: don’t use Toasts for critical messages!

One simple line of code is all that’s required to create a Toast:

Toast.makeText(this, "Your download has resumed.", Toast.LENGTH_LONG).show();

Again, the first parameter defines the context in which it’s displayed. The second is the message body and the last argument specifies how long the Toast should stay on screen. Only Toast.LENGTH_LONG or Toast.LENGTH_SHORT are accepted values – you can’t give it a time in seconds, as the duration is handled on a relative basis, so it could depend on user configuration.

Android-SDK-Notifications

Notifications

Notifications are the messages in the status bar at the top of the screen. They’re handy to do stuff like notifying the user of new, unread e-mail in a background service, even if he’s not currently inside the e-mail application (this is exactly what the GMail app does). The following is the code necessary to display a notification:

final int NOTIF_ID = 1234;

 NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 Notification note = new Notification(R.drawable.icon, "New E-mail", System.currentTimeMillis());

 PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, Main.class), 0);

 note.setLatestEventInfo(this, "New E-mail", "You have one unread message.", intent);

 notifManager.notify(NOTIF_ID, note);
 // notifManager.cancel(NOTIF_ID);

Let’s examine that big block of code piece-by-piece. First off, you’re going to need to grab an instance of the device’s NotificationManager, a system service.

    NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

The NotificationManager can send out – you guessed it – Notification objects. Create a new instance of one like this:

Notification note = new Notification(R.drawable.icon, "New E-mail", System.currentTimeMillis());

The first parameter is the resource ID of a Drawable (in this case I just used a dummy app icon that was automatically created). The second is the shortened title that will appear in the top status bar, not the one that you see when you expand the bar. Finally, the last parameter is the time that will be displayed in the Notification details.

Next, you’re going to create a PendingIntent object to specify what you want to happen when the notification is tapped on. Usually you’ll want to launch an activity in your application via an Intent:

PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

The first argument is the context, second is a private request code (don’t worry about it for now; according to the Android docs it isn’t used), third is an Intent object (in this case we’re having it start the MainActivity) and the last one is for flags (check the SDK docs for an explanation of these flags).

Now comes the juicy part. Using setLatestEventInfo you can specify a title, a message, and the Intent that will be invoked when users click on the notification in the expanded view.

note.setLatestEventInfo(this, "New E-mail", "You have one unread message.", intent);

All that’s left to do is create an int constant to store an ID so you can keep track of the notification. It’s up to you to choose the value for it -just make sure you’re not using duplicates. Call notify() and pass the ID along with the Notification object you created earlier:

final int NOTIF_ID = 1234;
notifManager.notify(NOTIF_ID, note);
Android-SDK-Notifications

One last thing to mention is that clicking on the notification in the expanded panel will not automatically clear it from the screen. You’re in charge of that. If you’re developing an email client for example, then the best time and place to cancel notifications is when the user has read the new emails or is at the Activity where all emails are listed. You can do so with a line of code like the following:

    notifManager.cancel(NOTIF_ID);

Add Comment

Discussion 9 Comments

  1. Soeren says:

    Hi,

    Sweet article! Really enjoyed reading it. Maybe you could help me out, as i'm trying to practice this a bit.

    If I want to make a toast on the "setNegativeButton" what do I do?

    I've tried

    .setNegativeButton("Cancel", negativeToast())

    private OnClickListener negativeToast() {

    // TODO Auto-generated method stub

    return Toast.makeText(this, "this is a negative onClick", Toast.LENGTH_LONG).show();

    }

    Any clue?

    Thanks,

    Soeren.

    • Hannes Holste says:
      Author

      Hey,

      A quick way to do it is to pass it an OnClickListener as an anonymous class.

      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      public void onClick(DialogInterface dialogInterface, int i) {

      Toast.makeText(getApplicationContext(), "this is a negative onClick", Toast.LENGTH_LONG).show();

      }

      }).show();

      These methods accept DialogInterface's OnClickListener, by the way, not the one from the View class. You'll also have to pass makeText() a context as the first parameter, because the "this" keyword will refer to the wrong thing here. (See my reply to Anders below for an explanation.)

      Generally if you're exploring things but aren't really sure how to approach them, it's always handy to refer to API documentation and to be assisted by IDE auto-completion. The API docs should be directly accessible in most big IDEs. (Eclipse: SHIFT+F2 for javadocs and CTRL+SPACE for auto-completion, if I remember correctly)

  2. Anders Gardebring says:

    Hi! I am desperately trying to get notifications to work, but it just will not work. I have tried maybe 10 different example codes and they all fail with parser errors (I dont even get to a compile stage with the code I try). (this in general seem to be a big problem on android, most of the code I try just will not work).

    Might this be an SDK thing? I am targetting my app towards android 1.6 (sdk 3) and I guess some of the code I see on sites are targeted towards later sdk versions?

    Just to take an example, there seem to be no constructor on intent matching

    "new Intent(this, Main.class). "

    Instead I get an error from eclipse saying

    "The constructor Intent(new View.OnClickListener(){}, Class) is undefined".

    static final NOTIF_ID = 1234; also gives an error "Syntax error on token final, invalid Type".

    PendingIntent.getActivity(…) gives me the error

    "The method getActivity(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (new View.OnClickListener(){}, int, Intent, int)"

    Any ideas on where I shoud look?

    • Anders Gardebring says:

      And about 2 minutes after I wrote the text above I finally found a snippet of code that actually worked for me. Check this link:
      http://www.helloandroid.com/tutorials/hello-baby-

    • Hannes Holste says:
      Author

      Hey Anders,

      sorry about NOTIF_ID, I did a few last-minute changes and it looks like I had accidentally chopped off the "int" keyword (Hence "Invalid/Nonexistant type"). It's supposed to be:

      static final int NOTIF_ID = 1234;

      Regarding the other errors: It looks like you're creating an intent within an OnClickListener. As such, the keyword "this" doesn't refer to the activity (context) anymore, but rather, the OnClickListener. You'll need to pass it an instance of an activity, either via a variable or by getApplicationContext() – it depends on your setup. Also, "Main.class" will have to be changed to the Class object of an activity.

      Here's an example (I placed this in the onCreate() method in the quick tip source code, where NOTIF_ID is defined as a constant at the top of the file):

      View.OnClickListener listener = new View.OnClickListener() {

      public void onClick(View view) {

      NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

      Notification note = new Notification(R.drawable.icon, "New E-mail", System.currentTimeMillis());

      PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), Main.class), 0);

      note.setLatestEventInfo(getApplicationContext(), "New E-mail", "You have one unread message.", intent);

      notifManager.notify(NOTIF_ID, note);

      }

      };

      // something.setOnClickListener(listener);

      Hope this clears things up!

      P.S.: It might also be helpful to download the project source code so you can quickly compile/tweak things without having to paste snippets from the tutorial.

      • Hannes Holste says:
        Author

        ** Note: If you declare NOTIF_ID in a method like onStart then the static keyword has to be removed.

  3. Irene says:

    Simply, Great. Thanks~

  4. serkan says:

    i can show new email count on status bar but
    i want to show new email count on application icon
    i searched 2 day but i couldn’t find anythink

  5. harsha says:

    Is it possible to show more than one notifications in notification bar.

    how can i show one after one notification in notification bar is it possible to show.
    please help me…….

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.