【问题标题】:can not read extra from intent when app startup from notification从通知启动应用程序时,无法从意图中读取额外信息
【发布时间】:2016-07-12 12:49:17
【问题描述】:

我正在使用 FCM 接收消息,并且在 onMessageReceived 我有代码

NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Service.NOTIFICATION_SERVICE);
            Intent notifyIntent = new Intent(this,HelloBubblesActivity.class);
            notifyIntent.putExtra("id",sender);
            notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notifyIntent, PendingIntent.FLAG_CANCEL_CURRENT);


            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(this)
                            .setContentTitle("New Message from " + name)
                            .setSmallIcon(R.drawable.smalllogo)
                            .setAutoCancel(false)
                            .setContentText(text)
                            .setContentIntent(pendingIntent);
            notificationManager.notify(sender, mBuilder.build());

当应用程序从通知中打开时,我遇到的问题是额外的问题是 -1,因为这里的代码

int chatId = getIntent().getIntExtra("id",-1); 

我错过了什么吗?

【问题讨论】:

  • 是你的sender 还是int
  • 是的,肯定是 int
  • 尝试在onNewIntent 中获取意图。
  • 我刚刚解决了,请看我的答案

标签: android android-intent notifications


【解决方案1】:

作为 FCM 文档

要接收消息,请使用扩展的服务 Firebase 消息服务。您的服务应该覆盖 onMessageReceived 回调,为大多数消息类型提供, 除了以下情况:

当您的应用在后台时发送的通知。在这个 在这种情况下,通知会发送到设备的系统托盘。一种 默认情况下,用户点击通知会打开应用启动器。留言 通知和数据有效负载。在这种情况下, 通知被传送到设备的系统托盘,并且数据 有效载荷是在您的启动器意图的附加内容中交付的 活动。

所以 onMessageReceived 将永远不会触发,如果应用程序在后台并且当您单击通知时 MainActivity 将启动,您所需要的只是获取意图并获取从服务器发送的 Extra

if (null != getIntent().getExtras() )
        {
            chatId = getIntent().getStringExtra("sender");
        }

【讨论】:

    【解决方案2】:

    确保您的 Activity 未启用单实例。有一段时间是单实例活动的问题

    【讨论】:

    • 我把它作为 android:launchMode="singleTask" 而不是作为 singleInstance,你认为这是问题吗??
    • 是的,我就是这样。可能是因为 Android 并没有真正刷新 Activity。它只是把它带到前面。请尝试覆盖 onNewIntent(Intent) 以拦截新 Intent 或将 android:launchMode="singleTask" 删除到您的 Activity
    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多