Android plays background music via StartService _android

Source: Internet
Author: User
Tags prepare

For a basic overview of the use of StartService and its lifecycle, see Overview of basic usage of StartService in Android.

By playing a simple example of background music, this article demonstrates the basic usage flow of startservice, which is as follows

The system interface is as follows:

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

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

Musicservice is a service for playing background music, and its code looks like this:

Package Com.ispring.startservicedemo;
Import Android.app.Service;
Import android.content.Intent;
Import Android.media.MediaPlayer;
Import Android.os.IBinder;

Import Android.widget.Toast;

Import java.io.IOException;

  public class Musicservice extends Service {private MediaPlayer MediaPlayer = null;

  Private Boolean isready = false;

    @Override public void OnCreate () {//oncreate will only call once Super.oncreate () in the life cycle of the service;
    Initialize Media Player MediaPlayer = Mediaplayer.create (this, r.raw.music);
    if (MediaPlayer = = null) {return;
    } mediaplayer.stop (); Mediaplayer.setonerrorlistener (New Mediaplayer.onerrorlistener () {@Override public boolean onError (Mediaplaye
        R MP, int what, int extra) {mp.release ();
        Stopself ();
      return false;

    }
    });
      try{Mediaplayer.prepare ();
    IsReady = true;
      catch (IOException e) {e.printstacktrace ();
    IsReady = false; } if (IsReady) {//Background music setMediaplayer.setlooping (True) for loop playback; @Override public int Onstartcommand (Intent Intent, int flags, int startid) {//every startservice that invokes the context will trigger
      Onstartcommand callback method//So Onstartcommand may be invoked multiple times in the life cycle of the service if (IsReady &&!mediaplayer.isplaying ()) {
      Play background music mediaplayer.start ();
    Toast.maketext (This, "Start playing background music", Toast.length_long). Show ();
  return start_sticky;
  The Bindservice method is not supported in @Override public IBinder onbind (Intent Intent) {//This service, so null return null is returned directly here; The OnDestroy callback method super is triggered @Override public void OnDestroy () {//When the Stopself method is executed inside the StopService or service that invokes the context.
    OnDestroy ();
      if (MediaPlayer!= null) {if (mediaplayer.isplaying ()) {//Stop playing music mediaplayer.stop ();
      //Release Media Player Resource Mediaplayer.release ();
    Toast.maketext (This, "Stop playing background music", Toast.length_long). Show ();

 }
  }
}

The musicactivity code looks like this:

Package Com.ispring.startservicedemo;

Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.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 music
      Intent Intent = New Intent (this, musicservice.class);
      StartService (intent);
      Exits the current Activity
      this.finish ();
    } else if (v.getid () = = R.id.btnstop) {
      //stop playing music
      Intent Intent = new Intent (this, musicservice.class);
      StopService (intent);}}


After we clicked the button "Play music and quit the activity," we first started the 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 want to destroy your current activity? We call the activity's finish method here not from a functional point of view, but rather from an understanding of the way the code is run: After the completion of the activity the current activity is destroyed, In the interface it looks like the current UI is gone and the application exits, but wait a moment and you'll hear the background music ringing. This is a feature of the service: service and activity, as well as a basic application component, the service does not rely on any activity can be alone without any UI interface in the case of idle quietly in the Android background.

After the StartService is invoked, the Android framework receives intent information, and the first time a Musicservice instance is created and the Musicservice OnCreate callback method is executed. OnCreate is invoked only once in the service lifecycle, and we initialize R.raw.music as a media player in its OnCreate method and invoke the prepare method of the media player. Then we set the player to loop playback status. 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 Sync method prepare ().

When the OnCreate method is invoked, Android automatically recalls its Onstartcommand method, which in fact triggers the Onstartcommand callback method every time the startservice of the context is invoked. So Onstartcommand may be called multiple times during the service life cycle. So we made a judgment in Musicservice's onstartcommand to determine whether the player is in play, and if the current player does not play, we call the player's Start method to play the background music.

When we clicked the button "Play music and quit the activity", Musicservice started up and played background music, but the activity was destroyed and the UI interface of the program was gone. To stop playing the background music, we need to click the application icon again, reopen Musicactivity, and then click the "Stop Playing music" button on the interface, at which point we'll call the activity's StopService method, Android After the framework receives the intent to stop the service, it recalls the Musicservice OnDestroy method, in which we stop playing music and release the media Player resources.

This article only through the play background music This simple example demonstrates through StartService to start the service basic usage flow, the code did not optimize, hoped that will be helpful to everybody study service.

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.