1. 播放音频
setSound()方法接收一个Uri参数,所以在指定音频文件时要先获取音频文件对应的URI。
例如每个手机/system/media/audio/ringtones目录下有很多音频文件,我们从中随便选一个文件,就可这样指定:
Notification notification = new NotificationCompat(this,"default")
...
.setSound(Uri.fromFile("/system/media/audio/ringtones/Luna.ogg"))) //ogg是一种音频压缩格式
.build();
2. 手机振动
vibrate属性:长整型数组,用于设置手机静止和震动的时长,以ms为单位。
小标为0的值表示手机静止的时长,下标为1的值表示手机整的的时长,下标为2的值又表示手机静止的时长…
想让手机在通知到来时振动1秒,然后静止1秒,再振动1秒,则可写成
Notification notification = new NotificationCompat(this,"default")
...
.setVibrate(new long[] {0,1000,1000,1000})
.build();
3. 控制LED灯显示
setLights()方法接收三个参数:第一个指定LED灯颜色;第二个指定LED灯亮起的时长,单位ms;第三个指定LED灯暗去的时长,单位为ms。
Notification notification = new NotificationCompat(this,"default")
...
.setLights(Color,GREEN,1000,1000)
.build();
也可直接使用通知的默认效果,他会根据当前手机环境来决定播放什么铃声,以及如何振动。
Notification notification = new NotificationCompat(this,"default")
...
.setDefaults(NotificationCompat.DEFAULT_ALL)
.build();
高级功能
setStyle()方法:接收一个NotificationCompat.Style参数,用来构建富文本信息,如长文字、图片。
- 在通知中显示一段长文字
在setStyle()方法中创建一个NotificationCompat.BigTextStyle对象,再调用它的bigText()方法将文字内容传入。
Notification notification = new NotificationCompat(this,"default")
...
.setStyle(new NotificationCompat.BigTextStyle().bigText(" Lion dancing with a history of more
2,000 years has been a form of traditional Chinese folk art. During the dancing, the two performers
actions of the body and tail. ));
.build();
运行结果如图
- 在通知里显示一张大图片
通过BitmapFactory的decodeResource()方法将图片解析成Bitmap对象,再传入bigPicture()就可以。
Notification notification = new NotificationCompat(this,"default")
...
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.big_image)))
.build();
运行结果
setPriority()方法:设置通知的重要程度。
该方法接收一个整形参数用于设置这条通知的重要程度,一共有5个常量值可选:
- PRIORITY_DEFAULT:表示默认的重要程度,和不设置的效果一样。
- PRIORITY_MIN:最低的重要程度,只有在特定场景下会显示。
- PRIORITY_LOW:较低的重要程度。
- PRIORITY_HIGH:较高的重要程度。
- PRIORITY_MAX:最高的重要程度。
例如:
Notification notification = new NotificationCompat(this,"default")
...
.setPriority(NotificationComapt.PRIORITY_MAX)
.build();