【发布时间】:2019-07-10 10:48:11
【问题描述】:
我想使用 FirebaseMessagingService 来处理来自服务器的推送通知。但是一开始并没有调用onCreate 函数。我认为该服务在应用程序启动时会自动初始化。另外,我开始从 firebase 云消息发送测试通知,但没有成功。
class PushNotificationService: FirebaseMessagingService() {
private lateinit var app: App
override fun onCreate() {
super.onCreate()
App.log("FireBaseMsg: starting service")
app = application as App
}
override fun onMessageReceived(msg: RemoteMessage?) {
super.onMessageReceived(msg)
App.log("FireBaseMsg: onMessageReceived")
val pNotification = msg?.notification
if (pNotification != null){
val title = pNotification.title
val text = pNotification.body
if (!title.isNullOrEmpty() && !text.isNullOrEmpty()){
val p = PushNotification(app, NOTIFICATION_CHANNEL_ID_PUSH, title = title, text = text)
p.fireNotification(NOTIFICATION_ID_PUSH)
}
}
}
override fun onNewToken(token: String) {
App.log("FireBaseMsg: Received token: $token")
//REGISTER TOKEN
app.regPushNotification(token, ::onNewTokenCallback)
}
private fun onNewTokenCallback(err: ApiCallError?){
if (err == null){
app.showToast(app.getString(R.string.notification_push_token_failed))
}
}
}
清单:
<service
android:name=".services.PushNotificationService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
【问题讨论】:
-
FirebaseMessagingService 会自动被调用。您将在
onNewToken内收到新令牌 -
但是 onNewToken 在开始时没有被调用
-
您使用的是哪个版本的库?
-
是的,重装了5次就解决了。这个新的谷歌缓存系统真的很烦人。即使在手动清除缓存和数据然后卸载我的应用程序之后,我的共享首选项和数据也会被缓存。此过程连续执行 5 次,第 6 次最终清除了我所有缓存的数据,最终导致 service oncreate 调用,一切正常。
-
旁注:您可以在
AndroidManifest.xml的Application标签下添加android:allowBackup="false"
标签: android firebase firebase-cloud-messaging