0%

Android 通知栏提示的实现

前言

通知栏的制作还是比较麻烦的,牵扯到版本问题。话不多说,直接上代码。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 通知栏
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// 构建, 应对高版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "whatever"; //根据业务执行,名字任起
String channelName = "whatever conent"; //这个是channelid 的解释,在安装的时候会展示给用户看
int importance = NotificationManager.IMPORTANCE_HIGH;
// 定制channel
NotificationChannel channel = new NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(channelId);
channel.enableLights(true);
channel.setLightColor(1);
channel.setSound(null,null);


notificationManager.createNotificationChannel(channel);

}
// 定制通知栏
Notification notification= null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
notification = new Notification.Builder(context,"whatever")
.setContentTitle("叮铃咚提示你") // 标题
.setContentText("时间到了!!!") // 内容
.setSubText("现在需要完成xxxx") // 下面的小字
.setTicker("叮铃咚日程表提醒你喽!") // 通知栏的状态栏标题
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setWhen(System.currentTimeMillis()) // 时间
.setShowWhen(true)
.setAutoCancel(true) // 点击后自动取消
.build();
}else{
notification = new Notification.Builder(context)
.setContentTitle("叮铃咚提示你") // 标题
.setContentText("时间到了!!!") // 内容
.setSubText("现在需要完成xxxx") // 下面的小字
.setTicker("叮铃咚日程表提醒你喽!") // 通知栏的状态栏标题
.setSmallIcon(R.drawable.ic_launcher_background)
.setWhen(System.currentTimeMillis()) // 时间
.setAutoCancel(true) // 点击后自动取消
.build();
}

// 调用执行通知栏
notificationManager.notify(1,notification);

简单说说:

  • 也是由于 Android 8.0 以上对通知栏进行的调整,增加了 chanel。
  • 因此针对版本,要做不同的配置处理。
  • 通知栏一定要设定的属性是,标题,内容,smallIcon,setWhen。
  • setWhen 中一般填的是当前的时间
  • 可以通过 PendingIntent 来制作点击通知栏后的弹出的操作,例如跳转的Activity。