通过使用开关来启用和禁用推送通知 [英] push notification enable and disable by using switch

查看:154
本文介绍了通过使用开关来启用和禁用推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using firebase push notification(FCM).. and I want to enable and disable notifications using a switch button.

为此,我具有共享的首选项来启用和禁用通知,但似乎我的逻辑根本无法正常工作.

For that I have shared preferences to enable and disable notifications but it seems my logic is not at all working.

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

It doesn't make any difference if the switch is turn on or off. I am still receiving notifications.

我需要帮助,谢谢.

活动:-

  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:---

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");

    }

}

preferencehelper:-

preferencehelper:--

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()
}

}

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

using the method of topic(need help ):---------

     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()
        }

    })

此代码的问题是,在关闭电源(切换按钮)后(打开时接收通知而关闭不接收)后,它最初不起作用(在关闭时都接收通知).

The problem of this code is it doesn't worked at first(it receives notification at on off both) after switching on off (switching buttons) it works(when on receives notification and off doesn't receive).

推荐答案

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

FirebaseMessagingService runs in the background even when the app's not in the foreground so you won't be able to get the preferences using applicationContext. You should use Topic messaging - https://firebase.google.com/docs/cloud-messaging/android/topic-messaging

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

Use this in your switch's change listener:

要启用推送通知-

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

要禁用推送通知-

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

通过这种方式,您将通知Firebase您不想获取有关特定主题的通知.

This way you will notify Firebase that you don't want to get notifications about a particular topic.

这篇关于通过使用开关来启用和禁用推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆