Vous êtes sur la page 1sur 10

Tutorials

Services

Products

Books
Blog
Donate
Contact us

TrainingBooks

Android Notifications - Tutorial


Lars Vogel
Version 2.4
Copyright 2009, 2010, 2011, 2012, 2013 vogella GmbH
12.06.2013
Using the Notification Manager in Android
This article describes how to use the Notification Manager in Android. It is based on Eclipse
4.2, Java 1.6 and Android 4.2.

Table of Contents
1. Prerequisites for this tutorial
2. Notification Manager
2.1. Notification Manager
2.2. Setting up Notifications
2.3. Canceling Notifications
3. Pending Intent
4. Example: NotificationManager

5. Support this website


5.1.
5.2. Questions and Discussion
6. Links and Literature
6.1. Source Code
6.2. Android Resources
6.3. vogella Resources

1. Prerequisites for this tutorial


The following assumes that you have already basic knowledge in Android development.
Please check the Android development tutorial to learn the basics.

2. Notification Manager
2.1. Notification Manager
Android allows to put notification into the titlebar of your application. The user can expand the
notification bar and by selecting the notification the user can trigger another activity.

2.2. Setting up Notifications


Notifications in Android are represented by the Notification class. To create notifications
you use the NotificationManagerclass which can be received from the Context, e.g.
an activity or a service, via the getSystemService() method.

NotificationManager notificationManager = (NotificationManager)


getSystemService(NOTIFICATION_SERVICE);

The Notification.Builder provides an builder interface to create


an Notification object. You use a PendingIntent to specify the action which should be
performed once the user select the notification.
The Notification.Builder allows you to add up to three buttons with definable actions to
the notification.

// prepare intent which is triggered if the


// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// build notification
// the addAction re-use the same intent to keep the example short
Notification n

= new Notification.Builder(this)

.setContentTitle("New mail from " + "test@gmail.com")


.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();

NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);

Android 4.1 supports expandable notifications. In addition to normal notification view it is


possible to define a big view which gets shown when notification is expanded. There are three
styles to be used with the big view: big picture style, big text style, Inbox style. The following
code demonstrates the usage of the BigTextStyle() which allows to use up to 256 dp.

String longText = "...";


Notification noti = new Notification.Builder(this).
.....
.setStyle(new Notification.BigTextStyle().bigText(longText))

2.3. Canceling Notifications


The user can dismiss all notification or if you set your notification to auto-cancel it is also
removed once the user selects it.
You can also call the cancel() for a specific notification ID on the NotificationManager.
The cancelAll() method call removes all of the notifications you previously issued.

3. Pending Intent
A pending intent is a token that you give to another application (e.g., notification manager,
alarm manager or other 3rd party applications), which allows this other application to use the
permissions of your application to execute a predefined piece of code.
To perform a broadcast via a pending intent, get a PendingIntent via
the getBroadcast() method of the PendingIntent class. To perform an activity via a
pending intent, you receive the activity via PendingIntent.getActivity().

4. Example: NotificationManager

Create a new project called de.vogella.android.notificationmanager with the activity class


called CreateNotificationActivity. Thisactivity should use the main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="createNotification"
android:text="Create Notification" >
</Button>
</LinearLayout>

Create the following result.xml layout file.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the result activity opened from the
notification" >
</TextView>
</LinearLayout>

Create a new activity called NotificationReceiverActivity with the following coding. Don't forget
to register the activity in theAndroidManfest.mf.

package de.vogella.android.notificationmanager;
import android.app.Activity;
import android.os.Bundle;
public class NotificationReceiverActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
}
}

Change the CreateNotificationActivity class to the following coding.

package de.vogella.android.notificationmanager;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class CreateNotificationActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void createNotification(View view) {
// Prepare intent which is triggered if the

// notification is selected
Intent intent = new Intent(this, NotificationReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
.setContentTitle("New mail from " + "test@gmail.com")
.setContentText("Subject").setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}

Run your application and press the button. A new notification is created. If you select it your
second activity will be displayed.

5. Support this website


This tutorial is Open Content under the CC BY-NC-SA 3.0 DE license. Source code in this
tutorial is distributed under the Eclipse Public License. See the vogella License page for
details on the terms of reuse.
Writing and updating these tutorials is a lot of work. If this free community service was helpful,
you can support the cause by giving a tip as well as reporting typos and factual errors.
Please consider a contribution if this article helped you. It will help to maintain our content
and our Open Source activities.

5.2. Questions and Discussion

If you find errors in this tutorial, please notify me (see the top of the page). Please note that
due to the high volume of feedback I receive, I cannot answer questions to your
implementation. Ensure you have read the vogella FAQ as I don't respond to questions
already answered there.

6. Links and Literature


6.1. Source Code
Source Code of Examples

6.2. Android Resources


Android Location API and Google Maps
Android and Networking
Android Homepage
Android Issues / Bugs
Android Google Groups

6.3. vogella Resources


vogella Training Android and Eclipse Training from the vogella team
Android Tutorial Introduction to Android Programming
GWT Tutorial Program in Java, compile to JavaScript and HTML
Eclipse RCP Tutorial Create native applications in Java
JUnit Tutorial Test your application
Git Tutorial Put all your files in a distributed version control system

Vous aimerez peut-être aussi