'How to start a foreground service from a respository

I have a single activity Kotlin-based app that starts a foreground service with:

applicationContext.startForegroundService(serviceIntent)

Next I bind to the service so that I can obtain an Ibinder object and communicate with it via messages (in both directions) using:

bindService(serviceIntent, myConnection, Context.BIND_IMPORTANT)

In the service's onCreate method I execute

startForeground(1, notification) // posts a persistent notification

So that the service will keep running even when the user is running another app. All this is working well.

Now I want to refactor the app to a single activity that hosts multiple fragments. I'd like to share the service between the fragments (several of them anyway). (I've got the fragments navigating cleanly.)

I'd like to follow the MVVM design pattern and put the start/stop service control in a repository class (as suggested by What is the right place to start a service in an MVVM architecture on Stackoverflow.

However, I can't seem to get it to work. I've tried the following (among other things!):

  import android.content.Intent
  import androidx.core.content.ContextCompat.startForegroundService

  class myRepository {

    fun initService() {

        val serviceIntent = Intent(this, MyService::class.java)
        startForegroundService(serviceIntent)
 
    }
  }

The first line in the function has "Intent" underlined in red with the message "None of the following functions can be called with the arguments supplied."

Also the closing parenthesis of the startForegroundService statement has a red underline that when hovered over says "No value passed for paramenter 'intent'." So something seems to be wrong with my Intent statement.

Is there something simple (hopefully) that I'm just missing? Does it have to do with the context of my repository?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source