简单过程
有一点相对可能比较重要的 高版本的Android的通知,必须要NotificationChannelId
低版本
NotificationCompat.Builder builder;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
...
int notificationId = new Random().nextInt(); //通知栏id
builder = new NotificationCompat.Builder(context);
builder.setContentTitle(title)
.setWhen(System.currentTimeMillis()) //设置通知时间戳
.setSmallIcon(R.mipmap.app_icon)
.setContentText(text)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) //设置将从系统默认值继承哪些通知属性 基本就是用来设置是否通知音效或者震动
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT)) //点击通知后的跳转
.setTicker(text) //收到通知后从顶部弹出精简版通知
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}) //自定义震动的频率
.setPriority(Notification.PRIORITY_HIGH); //设置通知的优先等级
manager.notify(notificationId, builder.build());
高版本
NotificationCompat.Builder builder;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
...
int notificationId = new Random().nextInt(); //通知栏id
String channelId = String.valueOf(new Random().nextInt()); //自己生成的用于通知栏的channelId,高版本必备
NotificationChannel mChannel = new NotificationChannel(channelId, "name", NotificationManager.IMPORTANCE_HIGH);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
manager.createNotificationChannel(mChannel);
builder = new NotificationCompat.Builder(context, channelId);
builder.setContentTitle(title)
.setWhen(System.currentTimeMillis()) //设置通知时间戳
.setSmallIcon(R.mipmap.app_icon)
.setContentText(text)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) //设置将从系统默认值继承哪些通知属性 基本就是用来设置是否通知音效或者震动
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT)) //点击通知后的跳转
.setTicker(text) //收到通知后从顶部弹出精简版通知
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}) //自定义震动的频率
manager.notify(notificationId, builder.build());
网友评论