android使用notification消息通知(工具类封装)

编程入门 行业动态 更新时间:2024-10-27 21:23:28

android使用notification<a href=https://www.elefans.com/category/jswz/34/1771421.html style=消息通知(工具类封装)"/>

android使用notification消息通知(工具类封装)

代码直接复制粘贴就可以用了,参数可以更具自己需求添加

private NotificationManager manager;private Notification notification;private static final String NORMAL_CHANNEL_ID = "my_notification_normal";private static final String IMPORTANT_CHANNEL_ID = "my_notification_important";/*** 实现包装方法(参数按自己需求来)* @param title 标题* @param content 内容* @param priorityType 通知级别:0为重要通知(有提示音),非0为普通通知(无提示音)*/public void sendNotify (String title, String content, int priorityType) {manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);NotificationChannel wsschannel; // channel(安卓8.0及以上才用到)String channel_id = IMPORTANT_CHANNEL_ID; // channelId用于绑定builder配置int priority = NotificationCompat.PRIORITY_LOW; // 通知级别// 判断是否8.0及以上版本,并选择发送消息的级别if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {if (priorityType == 0) {wsschannel = new NotificationChannel(IMPORTANT_CHANNEL_ID, "重要通知", NotificationManager.IMPORTANCE_HIGH);channel_id = IMPORTANT_CHANNEL_ID;} else {wsschannel = new NotificationChannel(NORMAL_CHANNEL_ID, "一般通知", NotificationManager.IMPORTANCE_LOW);channel_id = NORMAL_CHANNEL_ID;}manager.createNotificationChannel(wsschannel);}// 通知级别if (priorityType == 0) {priority = NotificationCompat.PRIORITY_HIGH;} else {priority = NotificationCompat.PRIORITY_LOW;}// 点击意图Intent intent = new Intent(this, MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);// 通知配置notification = new NotificationCompat.Builder(this, channel_id).setContentTitle(title) // 标题.setContentText(content) // 内容.setSmallIcon(R.mipmap.user) // 小图标.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.setting)).setPriority(priority) // 7.0 设置优先级.setContentIntent(pendingIntent) // 跳转意图.setAutoCancel(true) // 点击后自动销毁.build();// 给每个通知随机idint id = (int) ((Math.random() * 9 + 1) * (6));// 生成通知manager.notify(id , notification);}
// 示例
sendNotify("服务关闭", "服务关闭成功", 0);

更多推荐

android使用notification消息通知(工具类封装)

本文发布于:2023-11-15 11:53:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1599148.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:消息   通知   工具   android   notification

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!