- 获取通知管理器
- 延迟执行的Intent
- 创建notification对象
- 实例化通知栏构造器创建布局
- 显示
获取通知管理器
//获取通知管理器
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
延迟执行的Intent
//延迟执行的Intent
Intent intent = new Intent(context, DisplayActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
实例化通知栏构造器创建布局
//实例化通知栏构造器创建布局
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("通知啦")
.setContentText("通知通知通知通知通知通知通知通知通知通知")
.setContentIntent(pendingIntent)
.build();
显示
//显示
notificationManager.notify(0, notification);
取消
在跳到指定页面或者完成指定操作后取消
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
其他设置
播放音频
//Uri soundUri=Uri.fromFile(new File(""));手机文件
//手机设置的默认提示音
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.setSound(soundUri)//声音
设置振动
//数组下标为0的值标识手机静止的时长,下标为1的值代表手机振动的时长,下标为2的值又表示手机静止的时长
//这句代码意思是:立刻振动1秒,然后静止1秒,再振动1秒
long[] vibrate = {0, 1000, 1000, 1000};
notification.setVibrate(vibrate)//振动
闪烁灯
notification.setLights(Color.GREEN, 1000, 1000)//设置闪烁灯