create simple android notification

Notifications are a powerful tool in the Android developer’s toolkit, helping to keep your users up-to-date on events that are happening inside your application, even when they’re not looking at your app directly. A well-timed and useful notification is also a great way to tempt the user into launching your application – particularly if they haven’t visited your app in a while!

In this article, I’m going to show you how to get started with notifications by creating a very simple and straightforward notification that, when tapped, launches the user’s browser and boots up a website (bonus points if you can guess what that website is going to be!)

What goes into a notification?

As a bare minimum even the most simple of notifications must contain the following:

  • An icon. Your typical mobile app user is busy and always on the go – there’s no guarantee they’ll even have the time to read your notification’s text! That’s why users should be able to recognise your app’s notifications at a glance, from the icon alone. For this reason you’ll typically use your app’s icon for your notifications, but occasionally you may want to use a different image, for example if you’re developing a messaging app you may decide to use the sender’s profile picture instead. Create the image you want to use and then add it to you project’s ‘drawable’ folder.
  • Some title text. You can set a notification’s title either by referencing a string resource, or by adding the text to your notification directly.
  • Some detail text. This is the most important part of your notification, so this text must include everything the user needs to understand exactly what they’re being notified about – but remember that most mobile users are in a rush, so you should keep this detail text short and snappy, too! Again, you set this text either via a string resource, or by adding it to your application code.

There’s loads of other notification settings you can use, and although some of them are pretty important (such as using a PendingIntent to define what happens when the user taps the notification) they are all optional. These three things are all you technically need, in order to create a fully-functioning notification.

Creating your notification

Like everything in Android, notifications have evolved over time. If you want to take advantage of some of the newer notification features while remaining backwards compatible with Android 3.0 and earlier, you’ll need to use NotificationCompat and its subclasses. NotificationCompat is available as part of the Android Support Library, so the first step is opening your project’s module-level build.gradle file and adding the support library to the dependencies section:

dependencies {

...

compile "com.android.support:support-v4:24.1.1"

}

Once you’ve added the support library, you’re ready to create a basic notification:

package com.jessicathornsby.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.content.Context;

public class MainActivity extends AppCompatActivity {


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

public void sendNotification(View view) {

//Get an instance of NotificationManager//

NotificationCompat.Builder mBuilder =
 new NotificationCompat.Builder(this)
 .setSmallIcon(R.drawable.notification_icon)
 .setContentTitle("My notification")
 .setContentText("Hello World!");
 
 
// Gets an instance of the NotificationManager service//

NotificationManager mNotificationManager =

(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//When you issue multiple notifications about the same type of event, it’s best practice for your app to try to update an existing notification with this new information, rather than immediately creating a new notification. If you want to update this notification at a later date, you need to assign it an ID. You can then use this ID whenever you issue a subsequent notification. If the previous notification is still visible, the system will update this existing notification, rather than create a new one. In this example, the notification’s ID is 001//

NotificationManager.notify().

mNotificationManager.notify(001, mBuilder.build());
 }
}

To help you test that this notification is working correctly, open your project’s activity_main.xml file and create the following layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.jessicathornsby.myapplication.MainActivity">

<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Do it!"
 android:id="@+id/button"
 android:onClick="sendNotification"/>

</LinearLayout>

Now it’s time to put your notification to the test! Install your project on either a physical Android device or an AVD (Android Virtual Device).

notification app UI

To trigger the notification, simply give the button a tap – you should see a new ‘Hello World’ notification.

notification

Define your notification’s action

At this point, our notification looks the part but if you tap the notification then things fall apart, as this notification doesn’t actually do anything. This is a problem, because if you tap pretty much any other notification on your Android smartphone or tablet, then something will happen – usually, this something involves launching an Activity that’s related to the notification’s content, for example tapping on a ‘New email’ notification will launch the Gmail app.

While adding an action to your notification is optional, the reality is that the vast majority of applications add actions to their notifications, so it’s become a sort of unwritten rule – if a user taps your app’s notification and nothing happens, then chances are they’re going to be left feeling disappointed.

For this reason it’s highly recommended that you add at least one action to your notifications, so that’s exactly what we’re going to do.

You define a notification action using a PendingIntent. In this instance, I’m going to update our basic notification with a PendingItent that launches the user’s default browser app and boots up a website. Here’s the complete code:

package com.jessicathornsby.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.content.Context;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;

public class MainActivity extends AppCompatActivity {

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

public void sendNotification(View view) {

NotificationCompat.Builder mBuilder =
 new NotificationCompat.Builder(this);

//Create the intent that’ll fire when the user taps the notification//

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.androidauthority.com/"));
 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

 mBuilder.setContentIntent(pendingIntent);

mBuilder.setSmallIcon(R.drawable.notification_icon);
 mBuilder.setContentTitle("My notification");
 mBuilder.setContentText("Hello World!");

 NotificationManager mNotificationManager =

(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

mNotificationManager.notify(001, mBuilder.build());
 }
}

Make these changes to your code, then re-install the updated project on your Android smartphone, tablet or emulator. Trigger the notification again, but this time make sure to open the notification drawer and give the notification a tap – your device’s default browser should launch and take you directly to the Android Authority website (you’re welcome!)

Setting your notification priorities

Do you feel like multiple notifications are always vying for your attention? Maybe your smartphone is constantly buzzing, ringing, or flashing its LED lights, to the point where new notifications aren’t even something you get excited about anymore?

With us all installing more apps, and doing more activities on our Android devices than ever before, it’s easy to feel bombarded by notifications. So when you’re developing an app, how do you ensure that your most important notifications don’t get lost in the crowd? The answer is simple: notification priorities.

These handy new methods help Android devices sort their notifications more intelligently, so the most urgent notifications always end up on top of the pile.

The lower a notification’s priority, the more likely it is to be hidden from the user in certain situations (such as when they’re interacting with another application), whereas higher-priority notifications appear in a floating ‘heads-up’ window that interrupts whatever the user is currently doing. Notifications that have a high priority (specifically MAX, HIGH or DEFAULT) should also light up the Android device’s LED lights, making them even more difficult for the user to ignore.

If you don’t assign a priority to your notification, it’ll automatically be assigned PRIORITY_DEFAULT. Alternatively, you can let the Android system know exactly how important your notification is, using the setPriority() method. For example:

.setPriority(Notification.PRIORITY_MAX)

Going from highest priority to lowest priority, your options are:

  • You should only use this setting for time-critical and urgent notifications; these are usually events that the user must resolve before they can continue with the current task. Most applications won’t need to issue any priority_max notifications.
  • This level is typically reserved for important communications, such as instant messages or other chat events.
  • These are the notifications at the bottom of the heap, and tend to be related to background information. The system usually won’t show the user minimum priority notifications unless they go looking for them, for example by launching the detailed notification log (if you’re unfamiliar with the notification log, you can access it by long-pressing on your homescreen, selecting ‘Widgets,’ followed by ‘Settings shortcut’ and then selecting ‘Notification log.’)
notification log

An example of a notification log.

Wrap up

And that’s a wrap. Of course, in this post we’ve only covered the basics of creating and employing Android notifications. Depending on what kind of functionality you’re aiming to achieve in your app, you can go much deeper, but whether you’re using basic notifications or more advanced ones, make sure to be thoughtful when using this powerful tool.

Do you have any tips for creating Android notifications? Please share them in the comments below!