首页 > 解决方案 > Android - 如果用户打开通知并按下后退按钮,应用程序将关闭

问题描述

在我的应用程序中,我有一个帖子列表,用户可以在其中喜欢并查看喜欢该帖子的用户列表。如果有人喜欢某个帖子,则该帖子的所有者会收到一条通知(Firebase 云消息传递),该通知会将他带到喜欢的列表中。打开通知后,用户被带到喜欢列表,但如果他点击返回,应用程序被最小化并显示 android home

目标:

点击打开通知 -> 查看 LikedByActivity -> 按返回按钮 -> 查看 HomeActivity

当前状态:

点击打开通知 -> 查看 LikedByActivity -> 按返回按钮 -> 应用程序最小化

代码:

    override fun onMessageReceived(remoteMessage: RemoteMessage) {   

        remoteMessage.notification?.let { notification ->

            val notificationChannelId = getString(R.string.default_notification_channel_id)
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

            val intent = setIntent(remoteMessage)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or
                    Intent.FLAG_ACTIVITY_CLEAR_TASK

            val pendingIntent = PendingIntent.getActivity(this,
                    0,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT)

           
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            
            val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
                    .setContentTitle(notification.title ?: "")
                    .setContentText(notification.body ?: "")
                    .setSmallIcon(R.drawable.ic_stat)
                    .setSound(soundUri)
                    .setColor(ContextCompat.getColor(applicationContext, R.color.colorNotification))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)


            notificationManager.notify(0, notificationBuilder.build())

        }
    }

设定意图:

private fun setIntent(remoteMessage: RemoteMessage): Intent {
    val data = remoteMessage.data
    val type = data["type"]
    val postId = data["postId"]

    when (type) {
        LIKE -> {
            val intent = Intent(this, LikedByActivity::class.java)
            intent.putExtra("postId", postId)
            return intent
        }
        else -> {
            return Intent(this, NotificationsActivity::class.java)
        }
    }
}

我没有设置 parentActivityName 因为这个活动可以被其他几个活动打开

显现:

    <activity android:name=".activity.LikedByActivity" />

标签: androidandroid-intentfirebase-cloud-messagingandroid-notifications

解决方案


推荐阅读