android - 如何在 firebase 消息服务中添加 View ?

标签 android firebase kotlin

我正在使用 fcm 进行推送通知,每当推送通知到达时,我需要从服务向用户显示一个 View (即使应用程序被终止或在后台),我试图通过绘图来像 facebook messenger 风格一样overlays,我已经获得了制作overlays的权限(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()

如何解决这个问题?当我在哪个 broadcastreceiver 类中创建一个 View 时,这工作正常,但不适用于 firebase 服务类。

最佳答案

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

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

并在 fcmDrawOverlayService onCreate() 方法上对其进行充气。

关于android - 如何在 firebase 消息服务中添加 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184190/

相关文章:

java - Google Play 商店卡片 View

Firebase 消息传递,在哪里获取服务器 key ?

Android Studio 4.1 金丝雀 : Firebase Crashlytics breaks android project compilation

java - Kotlin 1.4.30 Apache beam 编译错误

android - 将 Espresso 与自定义 EditText 结合使用

android - 如果我只想在我的应用程序中横向放置,我应该删除纵向布局目录吗?

android - GreenDao Generator 类在生成模型和 Dao 类时出错。

android - Firebase onComplete 从未在后台进程中调用

Kotlin Actor 到 Actor 的通信

android - 指定为非null的参数为null:参数投影Content Provider Kotlin