Notification (通知)
通知(Notification)是Android系统中比较有特色的功能,当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可可使用通知来实现。
通知的基本使用
1. 创建通知管理器
/* 首先需要一个NotificationManager来对通知进行管理 调用Context的getSystemService()方法获取到。 getSystemService()方法接受的一个字符串参数用于确定系统的的哪一个服务。 */ NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2.创建通知渠道
/* 调用NotificationChannel创建通知渠道实例 并为它设置属性 */ //通知渠道的ID String id = "channel_01"; //用户可以看到的通知渠道的名字 CharSequence name = getString(R.string.channel_name); //用户可看到的通知描述 String description = getString(R.string.channel_description); //构建NotificationChannel实例 NotificationChannel notificationChannel = new NotificationChannel(id,name,NotificationManager.IMPORTANCE_HIGH); //配置通知渠道的属性 notificationChannel.setDescription(description); //设置通知出现时的闪光灯 notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); //设置通知出现时的震动 notificationChannel.enableVibration(true); notificationChannel.setVibrationPattern(new long[]{100,200,300,400,500,400,300,200,100}); //在notificationManager中创建通知渠道 notificationManager.createNotificationChannel(notificationChannel);
3.创建通知渠道组
/* 创建通知渠道组 */ //通知渠道组的ID String group = "my_group_01"; //用户课件的渠道组名称 CharSequence groupName = getString(R.string.group_name); //创建NotificationChannelGroup NotificationChannelGroup notificationChannelGroup = new NotificationChannelGroup(group,groupName); //添加到NotificationManager中 notificationManager.createNotificationChannelGroup(notificationChannelGroup);
4.创建通知
/* 使用Builder构造器来创建Notification对象 传入的第一参数是上下文对象 传入的第二参数是NotificationChannel的代号 */ Notification notification = new NotificationCompat.Builder(MainActivity.this,id) //指定通知的标题内容 .setContentTitle("This is content title") //设置通知的内容 .setContentText("This is content text") //指定通知被创建的时间 .setWhen(System.currentTimeMillis()) //设置通知的小图标 .setSmallIcon(R.drawable.ic_launcher_foreground) //设置通知的大图标 .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background)) //添加点击跳转通知跳转 .setContentIntent(pendingIntent) //实现点击跳转后关闭通知 .setAutoCancel(true) .build(); /* 调用NotificationManager的notify()方法将通知显示出来 传入的第一个参数是通知的id 传入的第二个参数是notification对象 */ notificationManager.notify(1,notification);
5.实现点击通知跳转
/* 实现点击通知跳转到相应的Activity */ //创建PendingIntent Intent intent = new Intent(MainActivity.this,MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
6.跳转后关闭通知
//实现点击跳转后关闭通知 .setAutoCancel(true)
通知中的特殊功能
.setsound()//添加音频
.setvibrate(new long[]{0,1000,1000,1000)//设置手机震动为。通知实现开始震动,震动1秒后,停止1秒后,再震动1秒。(需要添加震动权限)
.setLights(闪光灯颜色,LED灯亮起来的时长,LED灯暗去的时长)
.setDefaults(NOtification.DEFAULT_ALL)//设置为默认的效果
.setContentText("短通知文本")
.setStyle("长通知文本")//还可以实现添加图片
.setPriority()//实现通知的重要程度设置