android Notification跳转 getIntent()问题

本文探讨了在实现IM系统时遇到的一个常见问题:点击Notification后,getIntent()始终获取到的是第一次点击通知时传递的Intent。通过深入分析,发现是PendingIntent初始化时的requestCode参数设置不当导致的问题。文章提供了修正方案,并解释了如何通过改变requestCode值来解决此问题。

今天写IM推送,点击Notification跳转至聊天界面时,getIntent()始终获取到的是第一次点击notification时候传递过来的Intent.
问题出现的原因,是PendingIntent初始化参数问题。

错误代码

    PendingIntent intent = PendingIntent.getActivity(context,0,
                notificationIntent, 0);

这里写图片描述

我们主要看 requestCode这个参数,Google文档的解释是:发件人私有的请求码
请求码一样,getIntent()获取到的就是一样的。
所以改变requestCode的值即可

要实现 Android 消息通知的点击跳转查看功能,可以通过以下步骤实现: 1. 创建并显示通知 ```java // 创建一个 Intent Intent intent = new Intent(this, MyActivity.class); // 创建 PendingIntent PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // 创建通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) // 设置 PendingIntent .setAutoCancel(true); // 显示通知 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notificationId, builder.build()); ``` 在上述代码中,我们创建了一个 Intent,并将其与一个 PendingIntent 关联。当用户点击通知时,该 PendingIntent 会启动指定的 Activity(这里是 MyActivity)。 2. 在 Activity 中处理 PendingIntent 在 MyActivity 中,我们可以通过以下代码获取启动该 Activity 的 Intent: ```java Intent intent = getIntent(); ``` 在这个 Intent 中,可以包含一些额外的信息,例如通知的 ID、消息内容等。因此,我们可以通过这些信息来更新 UI,或者执行其他操作。 在上述代码中,我们只是获取了启动该 Activity 的 Intent。如果需要获取传递给 PendingIntent 的额外信息,可以使用以下代码: ```java Bundle extras = intent.getExtras(); if (extras != null) { // 读取传递的额外信息 String message = extras.getString("message"); int notificationId = extras.getInt("notificationId"); // 更新 UI 或执行其他操作 } ``` 在创建 PendingIntent 时,可以通过 Intent 的 putExtra() 方法将额外的信息传递给 PendingIntent。例如: ```java Intent intent = new Intent(this, MyActivity.class); intent.putExtra("message", "Hello World!"); intent.putExtra("notificationId", notificationId); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); ``` 这样,在启动 MyActivity 后,我们就可以通过 getIntent().getExtras() 方法获取到传递的额外信息。 以上就是 Android 实现消息通知的点击跳转查看的基本步骤和代码示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值