0

I'm making a music player and using a Service to playback audio files.

Is it correct to start the service in a Activity?

The service should start when a item in a list is being pressed, is it fine to put that onClick function in a Activity?

From my knowledge a ViewModel should handle onClick events, but the ViewModel can't start a Service since it doesn't have Activity context.

  • you can pass the activity from the view ([how to get activity in view](https://stackoverflow.com/a/68423182/3585796)) with your on click event and the view model will create the service – Phil Dukhov May 22 '22 at 11:44
  • @PylypDukhov Ok, if I understand it right I should add Context as a parameter to my Composable so I can send Context with the clickable. `fun MusicCard(music: MusicItem, setCurrentSong: (MusicItem, Boolean, Context) -> Unit)` – Simon Andersson May 22 '22 at 12:00
  • You can use AndroidViewModel instead of ViewModel so it has a `context` property built-in. – Tenfour04 May 22 '22 at 13:24
  • You'll keep a variable in your ViewModel that says whether the service has already started. Then you'll need a function called something like `handleClick(context)`, which you'll call in your Composable function's `onClick` handler. `@Composable`s expose a `LocalContext.current` object, so no need to create an extra context parameter in your Composable. Inside the `handleClick` function you created, check for the value of the tracking variable to see if the service is already started. If not, then start the service, or else, handle per your use-case. – Richard Onslow Roper May 22 '22 at 14:41

0 Answers0