有一段时间没有写Android学习笔记了,中间掉了很多内容,期待后面抽时间补上。今天写一个小播放器用到了Notification,顺便将这个类总结一下。
Android的通知用来提示用户的某个非紧急事件的发生,会在statusBar上面做出一些图片、文字的提示,打开通知栏之后能看到更多的信息,甚至是通过点击进入一个应用。
下面先来看看Notification这个类:
一、首先是一些常量:
public static final int DEFAULT_SOUND = 1; //采用默认的提示声音
public static final int DEFAULT_VIBRATE = 2; //采用默认的振动方式。如果需要振动需要打开VIBRATE权限
public static final int DEFAULT_LIGHTS = 4; // 采用默认的闪灯模式。
public static final int FLAG_ONGOING_EVENT = 0x00000002; // 放在通知栏的运行里
public static final int FLAG_INSISTENT = 0x00000004; // 一直进行
public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008; // 振一下或发个声音
public static final int FLAG_AUTO_CANCEL = 0x00000010; // 该通知能被状态栏清除按钮清除掉
public static final int FLAG_NO_CLEAR = 0x00000020; // 不能清除
public static final int FLAG_FOREGROUND_SERVICE = 0x00000040; // 到前台来运行的服务
public static final int FLAG_HIGH_PRIORITY = 0x00000080; // 高优先级,即使屏蔽了statusBar也出现。一般对于电话提醒使用。
CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent)
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.filemp3, "音乐播放器", System.currentTimeMillis());
notification.flags |= Notification.FLAG_NO_CLEAR;
Intent notificationIntent = new Intent(AudioPlayerActivity.this, AudioPlayerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "title", "content", pendingIntent);
notificationManager.notify(R.drawable.filemp3, notification);
五、在来看看google官方上的一些信息。
Notification从3.0开始引入了Builder类来构造一个通知,如果应用需要安装在较低版本,可以使用官方提供的兼容包,里面包含了NotificationCompat.Builder类来实现同样的功能。
Notification提供了两种显示方式,一种普通方式还有一种大图方式(从4.1开始支持)。
普通方式:
普通方式最为常用,其显示高度为64dp,即使您设置了更大的图标也只能显示这么高。其显示的大致格式见下图:
1. ContentTitle 2. LargeIcon 3.ContentText 4. ContentInfo 5. SmallIcon 6. Time (setWhen())
上面的6个部分的内容都可以在Notification中找到相应的设置方法,可以根据自己的需要设置相应的值。
大图方式:
大图方式从4.1开始支持,它其实就是在普通方式的基础上进行了一个扩展。当用户通过手势滑动操作后展开为大图方式,显示格式如下:
大图方式的显示内容跟普通方式差不多,就多了一个7:detail area。 这部分内容设置比较灵活,可以是图片、文字等,详细见官方文档。
六、下面再来看看如何创建一个通知。我们通过NotificationCompat.Builder.build()方法来创建一个通知对象,并使用NotificationManager.notify()方法将它传递给系统。
1.必须设置的一些参数:
上面已经介绍了一个Notification可以显示的信息,总共有6(7)项,实际在创建一个通知对象时不需要所有的元素都显示,但有几个是必须要设置的,它们及其对应的设置方法如下:
smallIcon —— setSmallIcon();
contentTitle —— setContentTitle();
contentText —— setContentText();
当然其它参数如果需要显示,也使用与其对应的方法来一一设置即可。
2.