【问题标题】:FirebaseMessagingService is not called on app start应用启动时未调用 FirebaseMessagingService
【发布时间】: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


【解决方案1】:

我在实现 FirebaseMessagingService 类时遇到了同样的问题

我的解决方案

Manifest.xml

<service
        android:name=".MyFirebaseMessagingServices"
        android:enabled="true"
        android:permission="com.google.android.c2dm.permission.SEND"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

如果您的清单服务部分一切正常,那么

  1. 卸载您的应用程序

  2. 文件 -> 使缓存无效/重新启动....

  3. 运行您的应用程序

【讨论】:

  • 非常感谢上一节关于卸载、使缓存失效和重新启动,然后运行应用程序的内容!经过数小时的研究,这是唯一能让我通过onNewToken 将注册令牌显示在日志中的方法。我不需要清单中的其他内容,只需要官方 FirebaseMessagingService 文档/教程中的最低限度声明。
猜你喜欢
  • 2018-10-01
  • 2022-10-06
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多