代码之家  ›  专栏  ›  技术社区  ›  Yevgen

如何在后台自定义打开/关闭推送通知并终止

  •  0
  • Yevgen  · 技术社区  · 6 年前

    我需要开发自定义关闭/打开推送通知。值“开”或“关”我从共享的引用中得到。

    在前台,关闭选项工作良好,因为它可以在OnMessageReceived中设置。

    但是如何为kill和background模式做这些选项呢?

    我使用邮递员发送推送通知。

    我在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 回复  |  直到 6 年前
        1
  •  1
  •   Sandip Fichadiya    6 年前

    我怀疑您的推送通知有效负载/内容包含 notification 像钥匙一样

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

    如果这是真的,那么您将不会收到 onMessageReceived 当你的应用程序被关闭,你的检查将不起作用的时候回调。为了防止出现这种情况,请移除 通知 从你的有效载荷只发送 data 在Android方面,它应该可以毫无变化地工作。

    你可以了解这种行为 HERE.