Android 如何在firebase消息服务中添加视图?
我正在使用fcm进行推送通知,每当推送通知到达时,我都需要从服务向用户显示视图(即使应用程序被关闭或处于后台),我试图像facebook messenger那样绘制覆盖图,我已经获得了制作覆盖图的权限(android.permission.SYSTEM\u ALERT\u WINDOW),这是我的服务课Android 如何在firebase消息服务中添加视图?,android,firebase,kotlin,Android,Firebase,Kotlin,我正在使用fcm进行推送通知,每当推送通知到达时,我都需要从服务向用户显示视图(即使应用程序被关闭或处于后台),我试图像facebook messenger那样绘制覆盖图,我已经获得了制作覆盖图的权限(android.permission.SYSTEM\u ALERT\u WINDOW),这是我的服务课 package com.radisolutions.radipeople.radihome.services import android.app.Service import
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类中创建一个视图时,这是正常工作的,但在firebase服务类上不起作用。最后我自己得到了解决方案,FirebaseMessagingService()没有用于膨胀视图的上下文,因此,我必须在onMessageReceived方法中启动一个服务,并从那里膨胀视图,如
val fcmDrawOverlayService = Intent(this@FCMMessageReceiverService, FcmDrawOverlayService::class.java)
startService(fcmDrawOverlayService)
并在fcmDrawOverlayService onCreate()方法上对其进行充气。可能是重复的而不是重复的,请再次阅读问题@ZoeI think@Zoe是正确的,他提到的stackoverflow问题的解决方案可以用来解决您的问题。这不是完全重复,但解决方案似乎是一样的。请尝试该解决方案并报告它是否对您有效。该解决方案在@Anhayt无效,我在浏览StackOverflow后问了这个问题,我明白了。当你尝试它时,你会遇到什么错误?另外,你能为你的问题添加代码吗?