Android 如何在后台执行自定义打开/关闭推送通知和终止
我需要开发自定义关闭/打开推送通知。我从SharedReferences获得的值“开”或“关” 在前台,关闭选项很有效,因为它可以在onMessageReceived中设置 但是如何在Kill和Background模式下实现这一点呢 我使用邮递员发送推送通知 我在FMC中的代码:Android 如何在后台执行自定义打开/关闭推送通知和终止,android,firebase-cloud-messaging,postman,android-push-notification,Android,Firebase Cloud Messaging,Postman,Android Push Notification,我需要开发自定义关闭/打开推送通知。我从SharedReferences获得的值“开”或“关” 在前台,关闭选项很有效,因为它可以在onMessageReceived中设置 但是如何在Kill和Background模式下实现这一点呢 我使用邮递员发送推送通知 我在FMC中的代码: class MyFirebaseMessagingService : FirebaseMessagingService() { private val CURRENT_PUSH = "currentPush" pri
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)
}
}
我怀疑推送通知负载/内容包含
通知
键
通知:{
“标题”:“这是标题”
}
如果这是真的,那么当您的应用程序被终止时,您将不会收到onMessageReceived
回调,因此您的检查将不起作用。为了防止出现这种情况,请从有效负载中删除通知
,只发送数据
,并且在android端它应该可以正常工作,不会发生任何更改
您可以准确地了解这种行为。谢谢