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 . 通知监听,可以参考监听系统收到的通知

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值