Android Service-based music player _android

Source: Internet
Author: User
Tags prepare

This paper develops a service based music player, the music is run by the background of the service is responsible for playback, when the background of the playback status changes, the program will be sent to notify the front desk Activity update interface; When you click the activity's Interface button, The system will change the playback status by sending a broadcast notification to the background service.

The foreground activity interface has two buttons to control play/pause, stop, and two text boxes to display the song name, the name of the singer, that is playing. The code for the foreground activity is as follows:

public class Mainactivity extends appcompatactivity implements view.onclicklistener{private ImageButton mstart;
  Private ImageButton mstop;
  Private TextView Mmusicname;
  Private TextView Msongername;
  Private Activityreceiver Mactivityreceiver;
  public static final String ctl_action = "Com.trampcr.action.CTL_ACTION";

  public static final String update_action = "Com.trampcr.action.UPDATE_ACTION";
  Define the music playback status, the 0X11 representative does not play, the 0x12 representative is playing, the 0X13 representative suspends int status = 0x11;
  string[] Musicnames = new string[]{"Perfect Life", "that year", "Hometown"};


  string[] Songernames = new string[]{"Xu Wei", "Xu Wei", "Xu Wei"};
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

    Setcontentview (R.layout.activity_main);
    Mstart = (ImageButton) Findviewbyid (R.id.start);
    Mstop = (ImageButton) Findviewbyid (r.id.stop);
    Mmusicname = (TextView) Findviewbyid (r.id.music_name);

    Msongername = (TextView) Findviewbyid (r.id.songer_name); Mstart.setonclicklisteneR (this);

    Mstop.setonclicklistener (this);
    Mactivityreceiver = new Activityreceiver ();
    Create Intentfilter intentfilter filter = new Intentfilter ();
    Specifies the ACTION filter.addaction (update_action) of the Broadcastreceiver listener;

    Registered Broadcastreceiver Registerreceiver (mactivityreceiver, filter);
    Intent Intent = new Intent (mainactivity.this, Musicservice.class);
  Start background Service StartService (intent); The public class Activityreceiver extends Broadcastreceiver {@Override the public void onreceive
      Tent Intent) {//Get update message in intent, update represents play status int update = Intent.getintextra ("Update",-1);
      Gets the current message in the intent, which represents the currently playing song int now = Intent.getintextra ("Present",-1);
        if (current >= 0) {mmusicname.settext (musicnames[current]);
      Msongername.settext (Songernames[current]);
       Switch (update) {case 0x11:mstart.setbackgroundresource (r.drawable.play);   status = 0x11;
        Break
          control system into the playback state case 0x12://In the playback state to set the use of the pause icon Mstart.setbackgroundresource (r.drawable.pause);
          status = 0x12;
        Break
          Case 0X13://Set to use Play Icon Mstart.setbackgroundresource (R.drawable.play) in a paused state;
          status = 0x13;
      Break
    @Override public void OnClick (View v) {Intent Intent = new Intent (ctl_action);
        Switch (V.getid ()) {case R.id.start:intent.putextra (' control ', 1);
      Break
        Case R.id.stop:intent.putextra ("Control", 2);
    Break
  //Send the broadcast, will be the service in the Broadcastreceiver received sendbroadcast (intent);

 }
}

Activityreceiver () is used in response to a broadcast from a background service that will change the playback status according to the messages in the broadcast intent and update the icon for the button in the program interface.

The onclick button sends a broadcast based on the clicked buttons, and the button ID is sent out when the radio is sent.

Next is the background service, which sends broadcasts when the playback status changes. The code is as follows:

public class Musicservice extends Service {myreceiver servicereceiver;
  Assetmanager Massetmanager;
  string[] musics = new string[]{"Prefectlife.mp3", "Thatyear.mp3", "Country.mp3"};
  MediaPlayer Mmediaplayer;
  int status = 0x11; int current = 0;
  Record the music that is currently playing @Nullable @Override public ibinder onbind (Intent Intent) {return null;
    @Override public void OnCreate () {super.oncreate ();
    Massetmanager = Getassets ();
    Servicereceiver = new Myreceiver ();
    Create Intentfilter intentfilter filter = new Intentfilter ();
    Filter.addaction (mainactivity.ctl_action);
    Registerreceiver (servicereceiver, filter);
    Create MediaPlayer Mmediaplayer = new MediaPlayer (); Complete event binding listener Mmediaplayer.setoncompletionlistener for MediaPlayer playback (new Mediaplayer.oncompletionlistener () {@Overrid
        e public void Oncompletion (MediaPlayer MP) {current++;
        if (current >= 3) {current = 0; }//Send broadcast notification activity changestext box Intent sendintent = new Intent (mainactivity.update_action);
        Sendintent.putextra ("current", current);
        Send a broadcast to be received by the broadcastreceiver in the Activity Sendbroadcast (sendintent);
      Prepare and Play Music Prepareandplay (Musics[current]);
  }
    }); The public class Myreceiver extends Broadcastreceiver {@Override the public void onreceive (context context, Intent I
      ntent) {int control = Intent.getintextra (' control ',-1);
            Switch (Control) {Case 1://Play or Pause//original No Play status if (status ==0x11) {//Ready to play Music
            Prepareandplay (Musics[current]);
          status = 0x12;
            ///Original play State else if (status = = 0x12) {//Pause mmediaplayer.pause (); status = 0x13; Change to paused state}//original paused else if (status = = 0x13) {//play Mmediaplayer.
            Start (); status = 0x12; Change Status} BreAk
            Stop Sound Case 2://If the original is playing or pausing if (status = = 0x12 | | status = 0x13) {//stop playing
            Mmediaplayer.stop ();
          status = 0x11;
      }//Broadcast notification activity change icon, text box Intent sendintent = new Intent (mainactivity.update_action);
      Sendintent.putextra ("Update", status);
      Sendintent.putextra ("current", current);
    Send a broadcast to be received by the broadcastreceiver in the Activity Sendbroadcast (sendintent); } private void Prepareandplay (String music) {try {//Open the specified music file Assetfiledescriptor Assetfiledescri
      Ptor = MASSETMANAGER.OPENFD (music);
      Mmediaplayer.reset (); Use MediaPlayer to load the specified sound file Mmediaplayer.setdatasource (Assetfiledescriptor.getfiledescriptor (),
      Assetfiledescriptor.getstartoffset (), assetfiledescriptor.getlength ()); Mmediaplayer.prepare (); Prepare sound mmediaplayer.start ();
    Play} catch (IOException e) {e.printstacktrace ();
 }
  }
}

Myreceiver is used to receive broadcasts from the foreground activity and to change the playback status of the service according to the broadcast message content, and when the playback status changes, the service sends out a broadcast, the broadcast message will be received by the foreground activity, The foreground activity will update the interface based on broadcast messages.

In order for the music player to play the song sequentially, the program adds a Oncompletionlistener listener to the MediaPlayer, which automatically plays the next song when the MediaPlayer playback is complete.

Run the program, the effect diagram is as follows:


The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.