Simple example of Android playing background music via StartService

Source: Internet
Author: User

An overview of the basic use of startservice and its life cycle can be found in the blog "StartService Usage and service life cycle" in Android.

This article demonstrates the basic use flow of startservice by playing a simple example of background music.

The system interface is as follows:

There are two buttons on the interface, "play Music and exit activity" and "stop music playing". In this example, we control the Musicservice play or stop playing music by manipulating the activity button.

I put a name Music.mp3 under the Resource Directory/res/raw folder, so that we can refer to the music file in the program by R.raw.music, the resource file placed in the/res/raw folder will keep the original face will not be compiled into binary.

The musicservice applies to the service that plays the background music, and its code is as follows:

 PackageCom.ispring.startservicedemo;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.media.MediaPlayer;ImportAndroid.os.IBinder;ImportJava.io.IOException; Public  class musicservice extends Service {    PrivateMediaPlayer MediaPlayer =NULL;Private BooleanIsReady =false;@Override     Public void onCreate() {//oncreate is only called once during the service life cycle        Super. OnCreate ();//Initialize Media PlayerMediaPlayer = Mediaplayer.create ( This, R.raw.music);if(MediaPlayer = =NULL){return;        } mediaplayer.stop (); Mediaplayer.setonerrorlistener (NewMediaplayer.onerrorlistener () {@Override             Public Boolean OnError(MediaPlayer MP,intWhat,intExtra) {mp.release (); Stopself ();return false; }        });Try{Mediaplayer.prepare (); IsReady =true; }Catch(IOException e)            {E.printstacktrace (); IsReady =false; }if(IsReady) {//Set the background music to play in a loopMediaplayer.setlooping (true); }    }@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {//Each call to the context StartService triggers the Onstartcommand callback method        //So Onstartcommand may be called multiple times during the service life cycle        if(IsReady &&!mediaplayer.isplaying ()) {//Play background musicMediaplayer.start (); }returnStart_sticky; }@Override     PublicIBinderOnbind(Intent Intent) {//The Bindservice method is not supported in this service, so NULL is returned here directly        return NULL; }@Override     Public void OnDestroy() {the OnDestroy callback method is triggered when the Stopself method is executed inside the StopService or service that invokes the context        Super. OnDestroy ();if(MediaPlayer! =NULL){if(Mediaplayer.isplaying ()) {//Stop playing musicMediaplayer.stop (); }//Release Media Player ResourcesMediaplayer.release (); }    }}

The code for Musicactivity is as follows:

 PackageCom.ispring.startservicedemo;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button; Public  class musicactivity extends Activity implements Button. Onclicklistener {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_music); }@Override     Public void OnClick(View v) {if(V.getid () = = R.id.btnstart) {//Play background musicIntent Intent =NewIntent ( This, Musicservice.class); StartService (Intent);//exit Current Activity             This. Finish (); }Else if(V.getid () = = R.id.btnstop) {//Stop playing musicIntent Intent =NewIntent ( This, Musicservice.class);        StopService (Intent); }    }}

After we clicked the button "play music and exited activity", we first started musicservice through the activity's startservice, and then we immediately called the activity's finish method to destroy the current activity. You may be asked why you are destroying your current activity? The finish method We call activity here is not from a functional point of view, but from the point of view of how the code is run: After executing the activity's finish method, the current activity is destroyed, The interface looks like the current UI is gone and the app exits, but wait a moment and you'll hear the background music ringing. This is a feature of the service: service, like activity, is also a basic application component that allows the service to run silently in the Android background without having to rely on any activity, without any UI interface.

After the StartService is called, the Android framework receives the intent message, first creating an instance of Musicservice, executing the Musicservice OnCreate callback method, OnCreate is only called once during the service life cycle, we initialize the R.raw.music as a media player in its OnCreate method, and invoke the prepare method of the media player. We then set the player to loop the playback state. It should be noted that in the actual production environment, we should register the player's Setonpreparedlistener and call the Prepareasync () method, in order to simplify the code, we only call the player's synchronization method prepare ().

After calling the OnCreate method, Android will automatically callback its Onstartcommand method, in fact, each call to the context StartService will trigger the Onstartcommand callback method, So Onstartcommand may be called multiple times during the service's life cycle. So we made a judgment in Musicservice's onstartcommand to determine if the player is in play, and if the current player does not play we only call the player's Start method to play the background music.

When we clicked the button "play Music and Quit Activity", Musicservice started to play the background music, but the activity was destroyed and the UI interface of the program disappeared. In order to be able to stop playing the background music, we need to click the application icon again, reopen Musicactivity, then click on the "Stop Playing music" button on the interface, we will call the activity StopService method, Android When the framework receives a intent to stop the service, it calls back Musicservice's OnDestroy method, in which we stop playing music and release the Media Player resource.

This article is just a simple example of playing background music to demonstrate that the service basic usage process is initiated through StartService, the code is not optimized, and we hope to help you learn the service.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Simple example of Android playing background music via StartService

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.