【发布时间】:2019-02-15 08:40:10
【问题描述】:
我在我的片段 (Kotlin) 上设置 sharedPreferences 值,然后我想在我的 FirebaseMessagingService (Java) 上使用这个值。当我设置值并销毁应用程序并再次打开时,我的片段没有任何问题。我可以看到设定值。所以我确信我的片段更新了 sharedPreferences 值。但是当我尝试在 FirebaseMessagingService 上使用该值时,我总是得到默认值。
这是我在 kotlin 类上的设置方式:
sharedPref = activity?.getSharedPreferences("com.xxx.xxx.xxx",Context.MODE_PRIVATE)!!
private fun sharedPrefWrite(boolean: Boolean){
with (sharedPref?.edit()) {
this!!.putBoolean("notf", boolean)
apply()
}
}
这很好用。
这是我在 FirebaseMessagingService 上获取这些数据的方式:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
preferences = getApplicationContext().getSharedPreferences("com.xxx.xxx.xxx",Context.MODE_PRIVATE);
if(preferences.getBoolean("notf",true))
sendNotification(remoteMessage.getNotification().getBody());
}
并且始终提供服务发送通知。
而且我没有在我的活动中启动此服务,它只是在 Manifest.xml 上的 Application 标签下;
<service android:name="com.xxx.xxx.xxx.newsFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
关于为什么我不能得到这个值的任何建议?谢谢
编辑:
我刚刚进行了几次调试,当应用程序恢复(在前台)时,firebase 服务正确获取值。但如果应用程序在后台(onPause)或应用程序被破坏,服务无法获取更正来自 SharedPreferences 的数据。
编辑 2
我从 FirebaseMessagingService 中删除了 onMessageReceived 函数,然后将该应用重新安装到我的设备上,当应用销毁时,即使没有“onMessageReceived”,我也会收到通知...
最后编辑
下面的解决方案
【问题讨论】:
-
尝试使用 commit() 而不是 apply()。
-
@rmanalo 还是一样
-
保存和检索几乎同时发生吗?根据我的经验,如果您保存一个偏好然后立即想要使用它,您可能无法获得您期望的价值。我有一个解决方法,但它不适用于您的情况,因为它们在不同的课程中。
-
@rmanalo 几秒钟后没有服务调用
-
您确定该首选项存在吗?当首选项不存在时,getBoolean 方法返回默认值事件。尝试使用 contains(String key) 来了解偏好是否存在
标签: android firebase service kotlin sharedpreferences