---
title: "Notification"
author: "wayfarer"
date: "2010-02-02T23:33:11Z"
tags: ["Android", "XML", "音乐"]
categories: ["移动开发"]
slug: "notification"
draft: false
lastmod: "2010-02-02T23:33:11Z"
id: 586166
url: "https://wayfarer.iteye.com/blog/586166"
---

***1. Notification构造器的参数*** 分别为：在状态条上显示的图标、文字和Notification的当前时间

```
// Choose a drawable to display as the status bar icon
int icon = R.drawable.icon;
 
// Text to display in the status bar when the notification is launched
String tickerText = “Notification”;
 
// The extended status bar orders notification in time order
// Notification显示的时间, currentTimeMills表示立即显示
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);
```

 

***2. setLatestEventInfo()用来配置Notification在扩展的状态窗口中的外观*** 。扩展的状态窗口将显示图标和在构造函数中传入的时间，以及显示Notification标题和Notification内容。Notification可通过指定PendingIntent来触发。

```
Context context = getApplicationContext();
 
// Text to display in the extended status window
String expandedText = “Notification Text”;
 
// Title for the expanded status
String expandedTitle = “Notification Title”;
 
// Intent to launch an activity when the extended text is clicked
Intent intent = new Intent(this, MyActivity.class);
 
PendingIntent launchIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, expandedTitle, expandedText, launchIntent);

// Notification显示时会伴随音乐
// Notification.DEFAULT_VIBRATE：振动；Notification.DEFAULT_ALL：音乐+振动
notification.defaults = Notification.DEFAULT_SOUND;
```

使用setLastestEventInfo可更新数据集以呈现最新的消息（例如，接收多个SMS消息时更新SMS的数目）。任何对Notification的变更都需要重新触发setLastestEventInfo。振动需要在AndroidManifest.xml里进行下类设定

&lt;uses-permission android:name="android.permission.VIBRATE"/&gt;

***3. Notification的触发和取消***

NotificationManager.notify()和NotificationManager.cancel()。

每一个Notification都有一个唯一的id，这个id是开发者来指定的。