Android 如何将SharedPreferes的价值转换为FirebaseMessagingService?
我想使用SharedReferences设计推送通知的自定义关闭/打开 如何从FirebaseMessagingService中的SharedReferences中获取值(true或false) 我的两个选项都不起作用:Android 如何将SharedPreferes的价值转换为FirebaseMessagingService?,android,firebase-cloud-messaging,sharedpreferences,Android,Firebase Cloud Messaging,Sharedpreferences,我想使用SharedReferences设计推送通知的自定义关闭/打开 如何从FirebaseMessagingService中的SharedReferences中获取值(true或false) 我的两个选项都不起作用: 直接从SharedPreferences获取值,但getPreferences在FMS中不起作用 将值从活动传递给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)
}
}
不确定什么上下文。模式\u PRIVATE
,因此您可能必须用应用程序上下文替换
然后
它开始起作用,但并不正确。结果显示在getBoolean中指定为默认值的值(CURRENT_PUSH,true)。已忽略SharedReferences中的正确值。很抱歉,昨晚太晚了,如果workfirst参数需要StringEdit,则已编辑的答案需要StringEdit,您只需更改为
GetSharedReferences()
?很遗憾,此选项不起作用。GetSharedReferences需要两个参数(字符串名,int模式)。那里的名称和模式是什么?
sPref = getSharedPreferences(CONTEXT)
return sPref!!.getBoolean(CURRENT_PUSH, true)