我正在使用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()
如何解决此问题?当我在其中的broadcastreceiver类中创建视图但在Firebase服务类上不起作用时,此方法正常工作。
答案 0 :(得分:0)
最后,我自己得到了解决方案,FirebaseMessagingService()没有上下文可以膨胀视图,因此我必须在onMessageReceived方法内部启动服务,然后从那里膨胀视图
val fcmDrawOverlayService = Intent(this@FCMMessageReceiverService, FcmDrawOverlayService::class.java)
startService(fcmDrawOverlayService)
并通过fcmDrawOverlayService onCreate()方法对其进行充气。