0

After reading around for hours, I am little bit unclear on how an Activity and a Foreground service can co-exists in an android app.

Taking example of a Music Player app -

I create an Activity for displaying the UI and controls for the music player, and the music player gets started into a Foreground service. Based on the articles I have read.

And based on this -

A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.

So, now at this time, if I have to perform any actions on UI in my Activity, why will I not see an ANR or any other kind of sluggishness, since the music and user actions are both happening on the UI thread ?

duskandawn
  • 646
  • 1
  • 10
  • 19
  • Quoting your quote, with emphasis added: "A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). **This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.**" So, make sure anything you do in the service that might be invoked originally on the main application thread gets done asychronously. – CommonsWare Aug 24 '16 at 15:38
  • Depends on the operation your service is performing. If something heavy duty is happening on the service, it is always advisable to start a new thread for that operation within the service to avoid any sluggishness. Another approach could be starting the service as an independent process but that of course will have its overhead in terms of communication with the application's process. You should put the blocking operations on a separate thread though. – Aneeb Khawar Aug 24 '16 at 15:39
  • Thank you, so here is my basic question specifically for a music player app, none of the articles are creating a new thread in the service for playing music. Like Here: http://stackoverflow.com/questions/29590703/should-an-apps-background-music-have-a-thread-of-its-own. Why is this not a requirement, when we will always have an activity backing up a music player ? – duskandawn Aug 24 '16 at 16:29
  • The `MediaPlayer` creates its own background thread to play the music. You can call the `MediaPlayer` methods from the main (UI) thread. – David Wasser Sep 01 '16 at 19:42

0 Answers0