Home > Back-end >  How to start a foreground service from a respository
How to start a foreground service from a respository

Time:02-18

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?

CodePudding user response:

When you call "this" you are refering the actual class; in this case 'MyRepository'. This class is not binded to any Android context so is not a valid parameter for your intent. You will need to inject the application context through the constructor.

Anyways, as far as MVVM is concerned, it does not say where a service should be started. Only depends on the function to be performed by the service. For example, a music service should not be started from a repository because repositories are supposed to connect to the data layer.

  • Related