我正在使用 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/