前言
通知栏的制作还是比较麻烦的,牵扯到版本问题。话不多说,直接上代码。
代码
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"; int importance = NotificationManager.IMPORTANCE_HIGH; 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。