如何在收到通知[FCM]时自动启动Android应用程序?

时间:2017-03-23 12:32:11

标签: android

我想在用户收到应用上的通知时自动启动应用,启动器图标上不会有任何点击操作。

2 个答案:

答案 0 :(得分:1)

onMessageReceived()方法中,您可以尝试添加startActivity(intent)代码。这样,当应用收到FCM消息时,它会启动应用。像这样......

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        startActivity(new Intent(this, MainActivity.class));
    }
}

答案 1 :(得分:1)

如果通知主体不包含"通知"在后台应用时,onMessageReceived()方法正常工作参数。所有数据都应粘贴在"数据"中。像这样:

{
    "to":"token",
    "priority":"high",
    "data": {
        "title": "Carmen",
        "text": "Популярные новости за сегодня!",
        etc..
    }
}

然后,您可以在代码中解析它并在通知中显示标题和文本。

例如:

override fun onMessageReceived(remoteMessage: RemoteMessage?) {
        Log.d("FirebaseService", "Receive notification: ${remoteMessage?.data}")
        remoteMessage?.let { showNotification(remoteMessage) }
    }

    private fun showNotification(remoteMessage: RemoteMessage) {
        val notificationModel: NotificationModel
                = getNotificationModelFromMessageData(remoteMessage.data)

        val intent = Intent(this, SplashActivity::class.java)
        intent.putExtra(NOTIFICATION_ARGUMENT, notificationModel)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

        val pendingIntent = PendingIntent.getActivity(
                this, NOTIFICATION_RECEIVE_REQUEST_CODE,
                intent, PendingIntent.FLAG_ONE_SHOT)

        val defaultNotificationSound: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notification: Notification
                = NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setContentTitle(notificationModel.title)
                .setContentText(notificationModel.text)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setSound(defaultNotificationSound)
                .build()

        val notificationManager: NotificationManager
                = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(NOTIFICATION_ID, notification)
    }

    private fun getNotificationModelFromMessageData(jsonData: MutableMap<String, String>): NotificationModel {
        return NotificationModel(
                jsonData[TITLE_PARAMETER] as String,
                jsonData[TEXT_PARAMETER] as String,
                jsonData[DAYS_PARAMETER] as String,
                jsonData[MESSAGE_ID] as String)
    }

希望有所帮助!