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
In this tutorial, we will cover all three notification types.
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();
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:
Describes an intended action or a confirmation, e.g. "Save" or "Yes".
Describes a "neutral" action such as "Close".
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:
And always remember to create at least one button so your dialog can be closed, otherwise you'll have frustrated users seeing this:
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();
Note: The most important methods have been covered here. For a full list of builder methods, visit the API Docs.
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.
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);
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: