Android通知无法通过PendingIntent打包的Intent将自定义数据传递给App

我有一个应用程序,它可以响应Firebase消息,在设备上发布通知,并且当用户点击通知时,应该使用Firebase消息附带的信息提示重新启动该应用程序(这是一个

// In response to onmessageReceived() in a FirebaseMessagingService object...
// 1. create the intent to bundle with the notification and add custom data
Context appContext = this.getapplicationContext();
Intent intent = new Intent(appContext,Mainactivity.class);
intent.putExtra("myData",myData); // myData is a simple string passed from FCM - verified it's correct
intent.addflags(Intent.flaG_actIVITY_CLEAR_TOP | Intent.flaG_actIVITY_SINGLE_TOP); // per docs/StackOverflow
intent.setaction(Intent.actION_VIEW);

// 2. package as a one shot pending intent that is fired when the user taps it in system notification list
int requestCode = (int) System.currentTimeMillis();
PendingIntent pendingIntent =
PendingIntent.getactivity(myactivity,requestCode,intent,PendingIntent.flaG_ONE_SHOT | PendingIntent.flaG_UPDATE_CURRENT); // tried with/without flaG_UPDATE_CURRENT

// 3. build a notification around launching the intent
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(appContext)
.setSmallIcon(R.drawable.mylogo)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setautoCancel(true)
.setsound(RingtoneManager.getDefaulturi(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);

// 4. send notification to the system
Notificationmanager notificationmanager =
(Notificationmanager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationmanager.notify((int) System.currentTimeMillis(),notificationBuilder.build());

已收到Firebase消息,并且通知已成功发送到系统通知服务。当用户点击通知时,该应用程序被带到前台,但其意图与最初传递给该应用程序的意图相同-即。没有将myData与意图捆绑在一起。我尝试在onResume和onCreate中检索意图,结果是相同的-它缺少与通知捆绑在一起的数据。

// Back in the Main activity
Intent intent = this.getIntent();
String myData = intent.getStringExtra("myData"); // always null
doaction(myData); // fails because myData always null

我一直在梳理StackOverflow和网络以寻找答案,到目前为止,我已经尝试了很多变体,但结果是相同的-myData从未转发过。

lvxh88 回答:Android通知无法通过PendingIntent打包的Intent将自定义数据传递给App

我不确定您如何收到新的Intent。您可以尝试 onNewIntent()。 这很大程度上取决于您如何在清单中设置活动。 如果将相同的活动实例放在最前面,则新的意图将在onNewIntent()中传递。 希望这会有所帮助。

本文链接:https://www.f2er.com/3156168.html

大家都在问