使用开关启用和禁用推送通知

2024-04-20

我正在使用 firebase 推送通知(FCM)..并且我想使用切换按钮启用和禁用通知。

为此,我共享了启用和禁用通知的首选项,但似乎我的逻辑根本不起作用。

开关打开或关闭没有任何区别。我仍然收到通知。

我需要帮助谢谢。

活动: -

  val sharedPreferences = getSharedPreferences("myname", MODE_PRIVATE)

    simpleSwitch.setChecked(sharedPreferences.getBoolean("SWITCH_PARTIDOS_STATE", false))

    simpleSwitch.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
        sharedPreferences.edit().putBoolean("SWITCH_PARTIDOS_STATE", isChecked).commit()
        if (isChecked) {
           // FirebaseMessaging.getInstance().subscribeToTopic("Partidos")

            Toast.makeText(applicationContext, "Activado Correctamente",
                Toast.LENGTH_LONG).show()
        } else {
          //  FirebaseMessaging.getInstance().unsubscribeFromTopic("Partidos")
            Toast.makeText(applicationContext, "Desactivado Correctamente",
                Toast.LENGTH_LONG).show()
        }
        PreferenceHelper.prefernceHelperInstace.setBoolean(applicationContext, Constants.MessageNotificationKeys.ENABLE_NOTIFICATION, true);

    })

firebasemessagingservice:---

  override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)
    if (PreferenceHelper.prefernceHelperInstace.getBoolean(getApplicationContext(),
            Constants.MessageNotificationKeys.ENABLE_NOTIFICATION, true)
    ) {
        Log.d("msg", "onMessageReceived: " + remoteMessage.notification?.body)
        val intent = Intent(this, HomeActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent =
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
        val channelId = "Default"
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(remoteMessage.getNotification()?.getTitle())
            .setContentText(remoteMessage.getNotification()?.getBody()).setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setStyle(NotificationCompat.BigTextStyle()
                .bigText(remoteMessage.getNotification()?.getBody()))

        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager?
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Default channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            manager!!.createNotificationChannel(channel)
        }
        manager!!.notify(0, builder.build())
    }
    else {
        Log.e("TAG", "ReactFireBaseMessagingService: Notifications Are Disabled by User");

    }

}

偏好助手:--

class PreferenceHelper private constructor() {
fun setBoolean(appContext: Context?, key: String?, value: Boolean?) {
    PreferenceManager.getDefaultSharedPreferences(appContext).edit()
        .putBoolean(key, value!!).apply()
}

fun getBoolean(
    appContext: Context?, key: String?,
    defaultValue: Boolean?
): Boolean {
    return PreferenceManager.getDefaultSharedPreferences(appContext)
        .getBoolean(key, defaultValue!!)
}

fun getInteger(appContext: Context?, key: String?, defaultValue: Int): Int {
    return PreferenceManager.getDefaultSharedPreferences(appContext)
        .getInt(key, defaultValue)
}


companion object {
    val prefernceHelperInstace = PreferenceHelper()
}

}

使用主题的方法(需要帮助):---------

     val sharedPreferences = getSharedPreferences("myname", MODE_PRIVATE)

    simpleSwitch.setChecked(sharedPreferences.getBoolean("SWITCH_STATE", false))

    simpleSwitch.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
        sharedPreferences.edit().putBoolean("SWITCH_STATE", isChecked).commit()
        if (isChecked) {
            // FirebaseMessaging.getInstance().subscribeToTopic("Partidos")
  FirebaseMessaging.getInstance().subscribeToTopic("main_notification");
         

            Toast.makeText(applicationContext, "enabled notification",
                Toast.LENGTH_LONG).show()
        }
        else {
            FirebaseMessaging.getInstance().unsubscribeFromTopic("main_notification");
            Toast.makeText(applicationContext, "disabled notification",
                Toast.LENGTH_LONG).show()
        }

    })

这段代码的问题是它一开始不起作用(它在打开和关闭时都收到通知),在打开关闭(切换按钮)后它起作用(当打开收到通知而关闭不收到通知时)。


FirebaseMessagingService即使应用程序不在前台,也会在后台运行,因此您将无法使用以下命令获取首选项applicationContext。 您应该使用主题消息传递 -https://firebase.google.com/docs/cloud-messaging/android/topic-messaging https://firebase.google.com/docs/cloud-messaging/android/topic-messaging

在交换机的更改监听器中使用它:

要启用推送通知 -

FirebaseMessaging.getInstance().subscribeToTopic("your_topic");

禁用推送通知 -

FirebaseMessaging.getInstance().unsubscribeFromTopic("your_topic");

这样,您将通知 Firebase 您不想收到有关特定主题的通知。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用开关启用和禁用推送通知 的相关文章

随机推荐