如何将SharedPrefereces的值转换为FirebaseMessagingService?

时间:2018-11-18 00:32:37

标签: android firebase-cloud-messaging sharedpreferences

我想使用SharedPreferences设计用于推送通知的自定义关闭/打开。

如何从FirebaseMessagingService中的SharedPreferences中获取值(真或假)?

我的选择均无效:

  1. 要直接从SharedPrefences获得价值,但是getPreferences在FMS中不起作用。

  2. 将值从活动传递给FirebaseMessagingService。但是如何?

也许有第三个选项会起作用。请帮助我。

以下是我的FirebaseMessagingService的代码文件

class MyFirebaseMessagingService : FirebaseMessagingService() {

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

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

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

override fun onNewToken(s: String?) {
    Log.i(C.T, "NEW_TOKEN" + s!!)
}

private fun loadCurrentPushNotification(): Boolean { //to read the status push notification from SharedPreferences
    sPref = getPreferences(Context.MODE_PRIVATE) //this is not working
    return sPref!!.getBoolean(CURRENT_PUSH, true)
}
}

1 个答案:

答案 0 :(得分:1)

 sPref = getSharedPreferences(CONTEXT)

不确定Context.MODE_PRIVATE是什么,因此您可能必须替换为应用程序上下文

然后

 return sPref!!.getBoolean(CURRENT_PUSH, true)