通知的创建
-
创建通知管理器
//getSystemService()在Context类或者ContextWrapper类有,一般通过继承后者来持有
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); -
创建通知渠道对象并将其注入到通知管理器
//创建渠道对象并指定id、名称和重要性;id将被通知管理器用来确定通知被哪个渠道对象执行
NotificationChannel notificationChannel1 = new NotificationChannel(CHANNEL1_ID, CHANNEL1_NAME,NotificationManager.IMPORTANCE_HIGH);
//设置是否锁屏可视
notificationChannel1.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
//将渠道对象注入到通知管理器
manager.createNotificationChannel(notificationChannel1); -
创建通知对象并通过.notify(int id, Notification notify)方法发送通知
Notification.Builder builder = new Notification.Builder(getApplicationContext(), CHANNEL1_ID)
.setContentTitle(notifyTitle).setContentText(notifyContent).setSmallIcon(R.mipmap.android_img);
manager.notify(notifyID,builder.build()); -
可以给Builder设置点击之后跳转的Activity和点击之后是否取消通知的显示
Intent intent = new Intent(getApplicationContext(),NotificationAction.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);builder.setAutoCancel(true).setContentIntent(pendingIntent);

浙公网安备 33010602011771号