如何启动前台服务,当应用程序没有运行Android

问题描述 投票:0回答:1

我正在开发一个应用程序,我使用Firebase从Firebase获得一些调用。在每次调用中,我都会得到一个消息数据,我用它来向我的服务器发出请求。从服务器的响应中,我必须实现一些类似于来电的功能,也就是一个通知和一个铃声。我试图用一个Service来实现这个功能。

override fun onMessageReceived(message: RemoteMessage) {
   apiManager.apiService(message.data["url"]).apiCall()?.let { mResponse ->
      mRepository.handleResponse(mResponse)
   }
}


// The repository
override fun handleResponse(response: MyReponse) {
        isAboveO(code = {
            println("New message isAboveO....")
            ContextCompat.startForegroundService(applicationContext, Intent(applicationContext, TestService::class.java) )
        }, other = {
            applicationContext.startService(Intent(applicationContext, TestService::class.java))
        })
    }

TestService是一个服务类,我必须启动服务并显示通知。

class TestService: Service() {
    override fun onCreate() {
        super.onCreate()
        isAboveO(code = {
            incomeCallNotification()
        }, other = {
            startForeground(1, Notification())
        })
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        startTimer();
        return START_STICKY;
    }

    override fun onDestroy() {
        super.onDestroy()
        stopTimerTask()
    }

    private fun incomeCallNotification() {
        NotificationCompat.Builder(this, "application_chanel").apply {
            setSmallIcon(R.drawable.ic_videocam_white_24dp)
            color = ContextCompat.getColor(this@TestService, R.color.colorPrimary)
            setContentTitle("Title")
            priority = NotificationCompat.PRIORITY_MAX
            setOngoing(true)
            setContentText("Context text")
        }.build().also {
            startForeground(2, it)
        }
    }

    private var timer: Timer? = null
    private var timerTask: TimerTask? = null
    private fun startTimer() {
        timer = Timer()
        timerTask = object: TimerTask() {
            override fun run() {
                println("Timer inside service")
            }
        }
        timer?.schedule(timerTask, 1000, 1000) //
    }

    private fun stopTimerTask() {
        timer?.cancel()
        timer = null
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}

而在宣言中,我已经宣布服务。

<service android:name=".services.TestService"
            android:enabled="true" />

当我收到来自Firebase的消息时,当应用程序根本没有运行时,我看不到服务的启动。我怎样才能做到这一点?

android firebase firebase-cloud-messaging android-notifications foreground-service
1个回答
0
投票

onMessageReceived() 如果应用程序被杀死,则永远不会被调用,你可以看到更多的 当应用程序处于后台时,Firebase onMessageReceived未被调用。

© www.soinside.com 2019 - 2024. All rights reserved.