【问题标题】:How to add view inside the firebase messaging service?如何在 Firebase 消息传递服务中添加视图?
【发布时间】:2019-01-14 15:15:07
【问题描述】:

我正在使用 fcm 进行推送通知,每当推送通知到达时,我都需要从服务向用户显示视图(即使应用程序被杀死或在后台),我尝试通过绘图来像 facebook messenger 风格那样做叠加层,我已经获得了制作叠加层的权限(android.permission.SYSTEM_ALERT_WINDOW),这是我的服务类

package com.radisolutions.radipeople.radihome.services

    import android.app.Service
    import android.content.Context
    import android.content.Intent
    import android.os.IBinder
    import android.util.Log
    import android.view.LayoutInflater
    import android.view.WindowManager
    import com.google.firebase.messaging.FirebaseMessagingService
    import com.google.firebase.messaging.RemoteMessage
    import com.radisolutions.radipeople.radihome.R

    class FCMMessageReceiverService : FirebaseMessagingService() {

        override fun onMessageReceived(remoteMessage: RemoteMessage?) {

           Log.i("naveen", remoteMessage?.notification?.body.toString())
            val view = LayoutInflater.from(applicationContext).inflate(R.layout.overlay_visitor_alert, null)
            val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val layoutParams = WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
            windowManager.addView(view, layoutParams)
        }

        override fun onCreate() {
            super.onCreate()

        }



    }

但在 windowmanager.addview 行会触发以下错误

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

如何解决这个问题?当我在哪个广播接收器类中创建一个视图时,这可以正常工作,但不适用于 firebase 服务类。

【问题讨论】:

  • 不是重复的,请再次阅读问题@Zoe
  • 我认为@Zoe 是正确的,他提到的stackoverflow 问题的解决方案可用于解决您的问题。它不是完全重复的,但解决方案似乎相同。请尝试该解决方案并报告它是否适合您。
  • 那个解决方案不起作用@Anhayt,我在浏览stackoverflow后问了这个
  • 我明白了。尝试时遇到什么错误?另外,您能否将代码添加到问题中?

标签: android firebase kotlin


【解决方案1】:

最后我自己得到了解决方案,FirebaseMessagingService() 没有上下文来膨胀视图,所以我必须在 onMessageReceived 方法中启动一个服务并从那里膨胀视图

val fcmDrawOverlayService = Intent(this@FCMMessageReceiverService, FcmDrawOverlayService::class.java)
startService(fcmDrawOverlayService)

并在 fcmDrawOverlayService onCreate() 方法上对其进行膨胀。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多