Search code examples
androidandroid-activityservicebackground-process

Can a Service access an Activity if it's not active


I'm making a MP3 player and I have ArrayLists of songs that need to be altered and added to, even while the player is not active or in the background.

Do I store these ArrayLists in the Service so it can update them when needed, or do I store them in the Activity so the UI can access them easier? I've seen tutorials doing it both ways, so I am confused on how to proceed.

I'm thinking that if an Activity is not visible or active, the Service cannot access them. So, all of the mp3 lists should be stored in the Service and bind the Activity to the Service so the UI can update?

A Service can access my other classes while the app is in the background, right?


Solution

  • In general you do all the background actions in the service. This means that all data/information that is necessary to do this action or is related to this action is also managed by the service. Your activities should only work as view or control possibility of your service.

    In your case for example the PlaylistActivity will ask the service for the current playlist and will just display it. (Only a view for the service).
    The PlayerActivity will get the current song playing, the current progress (e.g. in seconds), and the playing state (started/stopped). This information will be displayed in a typical player interface. But it will offer also controls to start or stop the song, jump to next or previous song or e.g. fast forward/backward. If the user clicks these controls it is simply forwarded to the service. (A view and control for the service)