Simple Example of playing audio in the background using the binding Service

Source: Internet
Author: User

1. Service

When the applicationProgramWhen you are no longer at the front-end and are not using it, you need to create a service to ensure that the audio is played continuously. A service is a component of an android application. It is used to run tasks in the background without interacting with users.

2. Local and remote services

There are several available service classes in Android. Local Service: it exists as a part of a specific application and can only be accessed and controlled through the application. Remote service is another type of service that can communicate with other applications for access and control. Here, only one local service is used to provide the audio playback function.

3. Local Service

The service class must inherit the Android. App. Service class. This class is an abstract class, so the onbind method must be implemented to extend it.

 
Public ibinder onbind (intent) {// todo auto-generated method stubreturn msbinder ;//*}

Generally, if you only implement simple services and do not implement "binding", you can choose return null.

 

There are three other methods to indicate the service lifecycle. oncreate and ondestroy do not need to be mentioned. Here we will focus on onstartcommand. The onstartcommand method is called every time startservice is called with the intention of matching a service, so it may be called multiple times. The onstartcommand method returns an integer that indicates how the operating system performs operations if the service is terminated. You can use start_sticky to indicate that if the service is terminated, the service will be restarted.

Public int onstartcommand (intent, int flags, int startid) {// todo auto-generated method stublog. V (TAG, "onstartcommand"); If (! Mediaplayer. isplaying () {mediaplayer. Start ();} return start_sticky; // return Super. onstartcommand (intent, flags, startid );}

 

 

Insert: The onstartcommand method is introduced from android2.0. Before that, the onstart method is used. The parameter of the onstart method is an intent and an integer that represents startid. It does not include the flags parameter of the int type and does not return values. If the target phone number runs before 2.0, you need to use the onstart method.

Note: Do not forget to add an entry to the configuration file to specify the service.

In the next step, we also hope to control the mediaplayer in the service through activities, while issuing commands is more complicated. To control mediaplayer, bindservice is used to bind the activity with the Service (unbindservice is used for unbinding ). Once this is done, because the activity and the service are running in the same process, you can directly call the methods in the service. If you are creating a remote service, you must take a further step.

// Start the music service playmusicserviceintent = new intent (this, musicservice. class); startservice (playmusicserviceintent); // serviceconnection is a serviceconnection object, which is an interface used to monitor the status of the bound service serviceconnection = new serviceconnection () {@ overridepublic void onservicedisconnected (componentname name) {// todo auto-generated method stubmusicservice = NULL;} // note that this method has passed in an ibinder object, it is actually created and submitted by the service itself @ overridepublic void onserviceconnected (componentname, ibinder Service) {// todo auto-generated method stubmusicservice = (musicservice. musicservicebinder) Service ). getservice () ;}}; // when binding a service, you need to input intent and serviceconnectionbindservice (playmusicserviceintent, serviceconnection, context. bind_auto_create );

We have created a private internal class in the service class, which inherits from the binder class and is used to return the service itself when requesting a connection to the service during an activity.

 

 

Public class musicservicebinder extends binder // * {musicservice getservice () {return musicservice. This ;}}

 

Now we have set up the foundation. You can add any features you like to the service. By binding the service, you can directly call the methods defined in the service. If you do not bind a service, we will not be able to do anything except start or stop the service.

CompleteCodeExample:

Code in the activity:

 // start the music service playmusicserviceintent = new intent (this, musicservice. class); startservice (playmusicserviceintent); serviceconnection = new serviceconnection () {@ overridepublic void onservicedisconnected (componentname name) {// todo auto-generated method stubmusicservice = NULL ;} @ overridepublic void onserviceconnected (componentname name, ibinder Service) {// todo auto-generated method stubmusicservice = (musicservice. musicservicebinder) Service ). getservice () ;}}; // bindservice (playmusicserviceintent, serviceconnection, context. bind_auto_create); // The music service control button musicbtn = (button) findviewbyid (R. id. musicon); musicbtn. setbackgroundresource (R. drawable. musicon); musicbtn. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubif (musicservice. isplaynow () {musicbtn. setbackgroundresource (R. drawable. musicoff); musicservice. pausemusic ();} else {musicbtn. setbackgroundresource (R. drawable. musicon); musicservice. resumemusic () ;}}); 

Service Code:

Public class musicservice extends Service implements oncompletionlistener {static final string tag = "playerservice"; mediaplayer; private final ibinder msbinder = new musicservicebinder (); // * Public class musicservicebinder extends binder // * {musicservice getservice () {return musicservice. this ;}@ overridepublic void oncreate () {// todo auto-generated method stub // super. oncreate (); log. V (Tag, "oncreate"); mediaplayer = mediaplayer. create (this, R. raw. music); mediaplayer. setoncompletionlistener (this) ;}@ overridepublic void ondestroy () {// todo auto-generated method stubif (mediaplayer. isplaying () {mediaplayer. stop ();} mediaplayer. release (); log. V (TAG, "ondestroy"); // super. ondestroy () ;}@ overridepublic int onstartcommand (intent, int flags, int startid) {// todo auto-generated method stublog. V (TAG, "onstartcommand"); If (! Mediaplayer. isplaying () {mediaplayer. start ();} return start_sticky; // return Super. onstartcommand (intent, flags, startid) ;}@ overridepublic ibinder onbind (intent) {// todo auto-generated method stubreturn msbinder; // *} @ overridepublic void oncompletion (mediaplayer) {// todo auto-generated method stub // stopself (); mediaplayer. start ();} public void pausemusic () {If (mediaplayer. isplaying ()){ Mediaplayer. Pause () ;}} public void resumemusic () {If (! Mediaplayer. isplaying () {mediaplayer. Start () ;}} public Boolean isplaynow () {return mediaplayer. isplaying ();}}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.