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


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

    1. private NotificationManager manager;
    2. private Notification notification;
    3. private static final String NORMAL_CHANNEL_ID = "my_notification_normal";
    4. private static final String IMPORTANT_CHANNEL_ID = "my_notification_important";
    5. /**
    6. * 实现包装方法(参数按自己需求来)
    7. * @param title 标题
    8. * @param content 内容
    9. * @param priorityType 通知级别:0为重要通知(有提示音),非0为普通通知(无提示音)
    10. */
    11. public void sendNotify (String title, String content, int priorityType) {
    12. manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    13. NotificationChannel wsschannel; // channel(安卓8.0及以上才用到)
    14. String channel_id = IMPORTANT_CHANNEL_ID; // channelId用于绑定builder配置
    15. int priority = NotificationCompat.PRIORITY_LOW; // 通知级别
    16. // 判断是否8.0及以上版本,并选择发送消息的级别
    17. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    18. if (priorityType == 0) {
    19. wsschannel = new NotificationChannel(IMPORTANT_CHANNEL_ID, "重要通知", NotificationManager.IMPORTANCE_HIGH);
    20. channel_id = IMPORTANT_CHANNEL_ID;
    21. } else {
    22. wsschannel = new NotificationChannel(NORMAL_CHANNEL_ID, "一般通知", NotificationManager.IMPORTANCE_LOW);
    23. channel_id = NORMAL_CHANNEL_ID;
    24. }
    25. manager.createNotificationChannel(wsschannel);
    26. }
    27. // 通知级别
    28. if (priorityType == 0) {
    29. priority = NotificationCompat.PRIORITY_HIGH;
    30. } else {
    31. priority = NotificationCompat.PRIORITY_LOW;
    32. }
    33. // 点击意图
    34. Intent intent = new Intent(this, MainActivity.class);
    35. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
    36. // 通知配置
    37. notification = new NotificationCompat.Builder(this, channel_id)
    38. .setContentTitle(title) // 标题
    39. .setContentText(content) // 内容
    40. .setSmallIcon(R.mipmap.user) // 小图标
    41. .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.setting))
    42. .setPriority(priority) // 7.0 设置优先级
    43. .setContentIntent(pendingIntent) // 跳转意图
    44. .setAutoCancel(true) // 点击后自动销毁
    45. .build();
    46. // 给每个通知随机id
    47. int id = (int) ((Math.random() * 9 + 1) * (6));
    48. // 生成通知
    49. manager.notify(id , notification);
    50. }
    1. // 示例
    2. sendNotify("服务关闭", "服务关闭成功", 0);

  • 相关阅读:
    计算机三级备考——数据库技术
    HTML如何制作公司网站首页(web前端期末大作业)
    每日学到 43 - JavaScript中BOM和DOM
    记一次oracle存储过程转mysql百万级数据量 java代码查询 插入修改过程
    C语言学习记录(十五)C预处理器和C库
    SpringBoot 25 整合 redis
    【JavaWeb第1次上机练习】安装Tomcat并在本地浏览器成功运行第一个Hello world网站
    PDF转图片怎么转?建议收藏这三种方法
    网络安全(黑客)自学
    2022 年杭电多校第九场补题记录
  • 原文地址:https://blog.csdn.net/weixin_42966151/article/details/134316854