简体   繁体   中英

Binding several activities to one service for audio player

I have a service called AudioService that extends android class Service. In addition I have 5 activities in my app. How can I bind my one Service to 3 of those Activities only?

What I am interested in is the ability to run the service while the user is viewing any of those three activities, but if they view anything else then the service is shut down.

For example, if the user clicks a button and goes into one of those 3 activities and the service is started. A Mediaplayer object can be started at that time. They can click other navigation buttons or the back button, and as long as they are viewing one of those 3 activities the music keeps on playing without interruption.

Use a shared atomic variable to communicate state with the service. That will allow it to stop / start playing the music.

  1. Declare a static AtomicBoolean on the service and a static method that can set / get the value of this boolean. This should track if the music is already playing. If set to true, the music is playing.

  2. When the user clicks on a button that takes them to an activity, use the onStart() method of that activity to check the value of this boolean. If it is false then the music is not playing. Set it to true. The method that sets it to true should also start playing the music.

  3. On the other 2 activities's onStart() method, set the value of the AtomicBoolean to false. The method on the service should now set the AtomicBoolean to false and release the mediaplayer.

The background service itself can keep running. Just rebuild the mediaplayer when you want to start the music again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM