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

一. 从应用层来分析

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

复制代码
//1.创建一个有跳转的通知

//创建一个 Intent,用于处理用户点击通知时的操作
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// 创建一个有跳转的通知,通过setContentIntent()设置跳转
NotificationCompat.Builder builderWithIntent = new NotificationCompat.Builder(context, "channel_id")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("有跳转的通知")
        .setContentText("点击将跳转到主界面")
        .setContentIntent(pendingIntent);

// 发送有跳转的通知
int notificationIdWithIntent = 1;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationIdWithIntent, builderWithIntent.build());


//2.创建一个没有跳转的通知

// 创建一个没有跳转的通知,不设置setContentIntent()
NotificationCompat.Builder builderWithoutIntent = new NotificationCompat.Builder(context, "channel_id")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("没有跳转的通知")
        .setContentText("这是一个普通通知");

// 发送没有跳转的通知
int notificationIdWithoutIntent = 2;
notificationManager.notify(notificationIdWithoutIntent, builderWithoutIntent.build());

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

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

二 . 从系统层来分析

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

复制代码
 Notification notification = sbn.getNotification(); //获得一个Notification对象
  if (notification.contentIntent != null) {
            //有跳转通知,通知设置了PendingIntent
           
        }else {
          //无跳转通知

        }

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

相关推荐
HEJOO92 小时前
MySQL 日期时间类型怎么选:DATE、DATETIME、TIMESTAMP、TIME、YEAR 全解析
android·数据库·mysql
风早爽太2 小时前
Android 开发笔记:封装 Fragment 的管理工具类
android·kotlin
峥嵘life3 小时前
Android 17 具体代码新特性总结
android·开发语言·网络
王者鳜錸5 小时前
Android 接入 AIKit 轻量版语音合成实战
android·交互·多语种·离线合成·多种发音人
『 时光荏苒 』5 小时前
SQL 中常用的查询条件分类汇总,每个都配有“大白话注释”和示例,方便你对照学习
android·java·开发语言
智购科技自动贩卖机6 小时前
自动售货机SaaS多租户数据库实战:分库分表与租户隔离~YH
android·java·linux·开发语言·javascript·网络
遥不可及zzz7 小时前
Android 接入 Helpshift SDK 详细教程(Java 实战):客服聊天、FAQ、用户登录及消息推送
android·helpshift
Digitally7 小时前
通过蓝牙将文件从 iPhone 传输到 Android
android
程序猿老A7 小时前
轻量应用服务器怎么配置mysql
android·mysql·adb
weixin_3947580316 小时前
CRMEB Pro 优惠券:下单怎么核销,取消/退款怎么返券
android