如何在后台执行“自定义打开/关闭推送通知”和“终止”

时间:2018-11-20 11:16:09

标签: android firebase-cloud-messaging postman android-push-notification

我需要开发自定义的关闭/打开推送通知。我从SharedPreferences获得的值为“ on”或“ off”。

在前景中,关闭选项效果很好,因为可以在onMessageReceived中进行设置。

但是如何在Kill和Background模式下使用此选项?

我使用Postman发送推送通知。

我在FMC中的代码:

class MyFirebaseMessagingService : FirebaseMessagingService() {

private val CURRENT_PUSH = "currentPush"
private var sPref: SharedPreferences? = null

override fun onMessageReceived(remoteMessage: RemoteMessage?) {
    super.onMessageReceived(remoteMessage)

    if(loadCurrentPushNotification()) {
        if (remoteMessage!!.data != null) sendNotification(remoteMessage)
    }
}

private fun sendNotification(remoteMessage: RemoteMessage) {
    val data = remoteMessage.data

    val title = data["title"]
    val content = data["content"]

    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val NOTIFICATION_CHANNEL_ID = "1234"

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        @SuppressLint("WrongConstant") val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID,
                "SA Notification",
                NotificationManager.IMPORTANCE_MAX)

        notificationChannel.description = "SA channel notification"
        notificationChannel.enableLights(true)
        notificationChannel.lightColor = Color.RED
        notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
        notificationChannel.enableVibration(true)

        notificationManager.createNotificationChannel(notificationChannel)
    }


    val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.sa_launcher)
            .setContentTitle(title)
            .setContentText(content)
            .setContentInfo("Breaking")

    notificationManager.notify(1, notificationBuilder.build())
}

private fun loadCurrentPushNotification(): Boolean { //to read the status push notification from SharedPreferences
    sPref = getSharedPreferences("pushesOnOff", Context.MODE_PRIVATE)
    return sPref!!.getBoolean(CURRENT_PUSH, true)
}

}

1 个答案:

答案 0 :(得分:1)

我怀疑您的推送通知有效内容/内容包含像

这样的notification

notification : { 'title':'This is title' }

如果这是真的,那么当您的应用被终止时,您将不会收到onMessageReceived回调,因此您的支票将无法使用。为了防止这种情况,请从有效负载中删除notification并仅发送data,它应该可以在android端进行任何更改。

您可以了解有关此行为HERE.