• Android 通知--判断通知是否有跳转


    一. 从应用层来分析       

           在 Android 中,可以通过 PendingIntent 来实现有跳转的通知和没有跳转的通知的区别。具体来说,有跳转的通知会设置一个 PendingIntent,当用户点击通知时会触发该 PendingIntent,打开指定的界面或执行特定的操作;而没有跳转的通知则不设置 PendingIntent,用户点击通知时不会有任何操作。

    1. //1.创建一个有跳转的通知
    2. //创建一个 Intent,用于处理用户点击通知时的操作
    3. Intent intent = new Intent(context, MainActivity.class);
    4. PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    5. // 创建一个有跳转的通知,通过setContentIntent()设置跳转
    6. NotificationCompat.Builder builderWithIntent = new NotificationCompat.Builder(context, "channel_id")
    7. .setSmallIcon(R.drawable.notification_icon)
    8. .setContentTitle("有跳转的通知")
    9. .setContentText("点击将跳转到主界面")
    10. .setContentIntent(pendingIntent);
    11. // 发送有跳转的通知
    12. int notificationIdWithIntent = 1;
    13. NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    14. notificationManager.notify(notificationIdWithIntent, builderWithIntent.build());
    15. //2.创建一个没有跳转的通知
    16. // 创建一个没有跳转的通知,不设置setContentIntent()
    17. NotificationCompat.Builder builderWithoutIntent = new NotificationCompat.Builder(context, "channel_id")
    18. .setSmallIcon(R.drawable.notification_icon)
    19. .setContentTitle("没有跳转的通知")
    20. .setContentText("这是一个普通通知");
    21. // 发送没有跳转的通知
    22. int notificationIdWithoutIntent = 2;
    23. notificationManager.notify(notificationIdWithoutIntent, builderWithoutIntent.build());

            在上面的代码中,首先创建了一个有跳转的通知,并设置了一个 PendingIntent,用于处理用户点击通知时的操作。然后创建了一个没有跳转的通知,没有设置任何 PendingIntent。最后使用 NotificationManager 分别发送这两个通知。

           通过这种方式,用户点击有跳转的通知时会打开指定的界面(比如 MainActivity),而点击没有跳转的通知时则不会有任何操作。

    二 .  从系统层来分析

            通过监听系统通知,可以得到系统通知接口返回的通知参数 StatusBarNotification sbn, 代码如下:

    1. Notification notification = sbn.getNotification(); //获得一个Notification对象
    2. if (notification.contentIntent != null) {
    3. //有跳转通知,通知设置了PendingIntent
    4. }else {
    5. //无跳转通知
    6. }

          通过判断通知中的contentIntent 是否为空来区分通知是否设置了跳转,contentIntent 类型为PendingIntent . 通知监听,可以参考监听系统收到的通知

  • 相关阅读:
    HTML5数据推送SSE原理及应用开发
    计算机网络实验一 交换网络组建
    24_ue4进阶末日生存游戏开发[按路径巡逻]
    百度智能云千帆大模型平台再升级,SDK版本开源发布!
    2023江苏省领航杯(部分CRYPTO题目复现)
    opencv最大值滤波(不局限于图像)
    阿里云视频点播
    ubuntu20.04使用kubeadm安装kubernetes1.24.4
    Python爬虫(十八)_多线程糗事百科案例
    你知道 TCP 为什么要三次握手吗?
  • 原文地址:https://blog.csdn.net/Smile_729day/article/details/136337821