【问题标题】:Firebase: How to handle click on notification if notification was sent by serverFirebase:如果通知是由服务器发送的,如何处理点击通知
【发布时间】:2020-06-09 11:46:17
【问题描述】:

我正在使用我的 Java 后端向 Android 设备发送通知。

Android 设备收到通知,当我点击它时,它会打开我的应用程序。

到目前为止一切顺利,但我想要实现的是能够从 MainActivity 类的 onCreate() 方法中的 Firebase 消息中读取数据。这怎么可能?

private fun sendNotification(messageBody: String) {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT)

        val channelId = "" // TODO CHANNEL ID NEEDED
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
    }

这不会为我记录任何内容(在 onCreate() 中):

if (getIntent() != null) {
       val dataBundle = getIntent().extras
       Log.d("data bundle", dataBundle.toString())
   }

【问题讨论】:

标签: android firebase push-notification notifications


【解决方案1】:

首先,检查您可以发送的 2 种不同类型的通知。 link

根据您的应用程序的每种类型和状态(后台或前台),您不能总是从通知中获取数据,请查看此link2 了解更多信息。

当您的应用程序收到通知时,会有一个服务带有您可以覆盖以获取数据的方法。该方法称为 OnMessageReceived(RemoteMessage),您可以在link2 找到有关该服务的更多信息。

这是获取通知数据的方式。如果您想要 Activity 中的数据,有一些方法可以实现。您可以尝试将它们保存在数据库(持久)或SharedPreferences 并在您的活动启动时访问它们,或者您可以通过捆绑包将数据传递给您即将打开的活动(深度链接),检查此 stackoverflow @987654325 @。

【讨论】:

  • 好的,谢谢。但是,如果我想在应用处于后台并点击通知时执行特定操作怎么办?
  • 您可以使用 PendingIndend 来做到这一点。而不是您的 MainActivity 创建一个 IntentService 类。例如:public class SimpleTaskIntent extends IntentService { public SimpleTaskIntent() { super("SimpleTaskIntent"); } @Override protected void onHandleIntent(@Nullable Intent intent) { if (intent == null) return; MyData data = (MyData) intent.getSerializableExtra("my_data"); if (data == null) return; //Do something with your data... } } 不要忘记在清单中添加服务。
猜你喜欢
  • 2019-10-30
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
相关资源
最近更新 更多