现在的位置: 首页 > 综合 > 正文

Android 用户界面—状态栏通知(一)

2013年08月28日 ⁄ 综合 ⁄ 共 1604字 ⁄ 字号 评论关闭

状态栏通知(Status Bar Notifications

状态栏图标把一个图标添加到系统的状态栏(带有一个可选的文本提醒消息),并且还在通知窗口中添加一个通知消息。当用户选择这个通知时,Android系统会触发一个由通知定义的Intent对象(通常是要启动一个Activity)。你也能够在设备上给通知配置声音、震动、屏幕闪烁等效果来提醒用户。

状态栏通知应该用于后台服务要求用户响应有关事件的场景中。为了接受用户的交互,后台服务不应该自己启动Activity。相反,服务应该创建一个状态栏通知,当用户选择这个通知时,才启动对应的Activity

1在状态栏的左侧显示一个带有通知图标的状态栏。

1.带有通知的状态栏

2显示通知窗口中的通知消息。

2.通知窗口

基础

ActivityService对象能够初始化一个状态栏通知。因为Activity仅能够在前台运行且窗口有焦点时才能执行操作,所以通常是由Service对象来创建状态栏通知。这种方式下,当用户正在使用另一个应用程序或设备休眠时,通知也能够从后台创建。要创建通知,必须使用两个类:NotificationNotificationManager

使用Notification类的一个实例来定义状态栏通知的属性,如状态栏图标、通知消息,以及另外的如播放声音的设置等。NotificationManager对象是Android系统的服务,它执行和管理所有状态栏通知。你不需要直接实例化NotificationManager对象。为把通知发给它,必须用getSystemService()方法获得NotificationManager对象的引用,然后再想要通知用户的时候,用notify()方法把Notification对象传递给它。

以下是创建一个状态栏通知的方法:

1.  获得NotificationManager对象的引用:

String ns = Context.NOTIFICATION_SERVICE;

NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

2.  初始化Notification对象:

int icon = R.drawable.notification_icon;

CharSequence tickerText = "Hello";

long when = System.currentTimeMillis();

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

3.  定义通知消息和PendingIntent对象:

Context context = getApplicationContext();

CharSequence contentTitle = "My notification";

CharSequence contentText = "Hello World!";

Intent notificationIntent = new Intent(this, MyClass.class);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

4.  Notification对象传递给NotificationManager

privatestaticfinalint HELLO_ID
=1;

mNotificationManager.notify(HELLO_ID,
notification
);

到此为止,用户已经收到通知了。

抱歉!评论已关闭.