通知Notification小记

本文详细介绍如何在安卓应用中创建并管理通知栏通知,包括获取通知管理器、使用延迟执行Intent、创建及显示Notification对象等步骤,并介绍了如何设置通知的声音、振动及闪烁灯效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 获取通知管理器
  2. 延迟执行的Intent
  3. 创建notification对象
  4. 实例化通知栏构造器创建布局
  5. 显示

获取通知管理器

//获取通知管理器
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)//设置闪烁灯

代码截图

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值