Android based on development service music player

Source: Internet
Author: User

This is a service component based music player, the program's music will be played by the service components in the background, when the background of the playback state changes, the program will send a broadcast notification foreground activity update interface When the user clicks the foreground activity's interface button or drags the progress bar, the system changes the playback status and plays the specified music by sending a broadcast notification background service.

Program execution:


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzmvuz3l1emhlbmdmyw4=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast "alt=" Music player Project Structure "width=" "height=" 480 ">

Program code:

Program Interface Class (Musicbox.java):

Package Com.jph.musicbox;import Com.jph.util.constutil;import Android.os.bundle;import android.app.Activity;import Android.app.alertdialog;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.view.layoutinflater;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.imagebutton;import Android.widget.linearlayout;import Android.widget.seekbar;import Android.widget.seekbar.onseekbarchangelistener;import android.widget.textview;/** * Describe:</br> * </br > Service-based music advertisement * </br> This application is mainly implemented: * </br>1. Play related control information through the foreground activity, in the form of broadcasts * </br> The service that is passed to the backend. The service behind the scenes is responsible for music playback. * </br> is responsible for receiving background broadcasts to update the song name and the name of the singer on the playback interface. * </br>2. Show the current playback position through the progress bar, when the user drags the progress bar * </br> Control by Onseekbarchangelistener event * </br> The MediaPlayer in the background plays the music at the specified location.

* </br> @author JPH * </br>date:2014.08.07 * */public class MusicBox extends Activity {ImageButton btnplayorpa use,btnpre,btnnext;//progress bar static SeekBar skbmusic;//get interface display song title, author text box TextView title, author; string[] Titlestrs = new string[] {"Tao still", "rape", "You is the One"}; string[] Authorstrs = new string[] {"Mao Ning", "Dragon", "Unknown Artist"};//is playing Boolean isplaying=false; @Overrideprotected void Oncreat E (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); SkbMusic= (SeekBar ) Findviewbyid (R.id.skbmusic); Skbmusic.setonseekbarchangelistener (Schangelistener); btnNext= (ImageButton) Findviewbyid (R.id.btnnext); btnplayorpause= (ImageButton) Findviewbyid (r.id.btnplayorpause); btnpre= (ImageButton) Findviewbyid (R.id.btnpre); Btnnext.setonclicklistener (listener); Btnplayorpause.setonclicklistener (listener); Btnpre.setonclicklistener (listener); title= (TextView) Findviewbyid (r.id.title); author= (TextView) Findviewbyid ( R.id.author); Title.settext (Titlestrs[0]); Author.settext (Authorstrs[0]); Register receiver Musicboxreceiver Mreceiver=new musicboxreceiver (); Intentfilter filter=new intentfilter (); Filter.addAction ( constutil.musicbox_action); Registerreceiver (mreceiver, filter);//start Background serviceintent intent=new intent (this, Musicservice.class); StartService (intent);} Onclicklistener listener=new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method stubs Witch (V.getid ()) {case r.id.btnnext://next btnplayorpause.setbackgroundresource (r.drawable.state_pasue); Sendbroadcasttoservice (Constutil.state_next); Isplaying=true;break;case r.id.btnplayorpause://Play or pause if (!isPlaying ) {Btnplayorpause.setbackgroundresource (r.drawable.state_pasue); Sendbroadcasttoservice (ConstUtil.STATE_PLAY); Isplaying=true;} else {btnplayorpause.setbackgroundresource (r.drawable.state_play); Sendbroadcasttoservice (ConstUtil.STATE_PAUSE) ; isplaying=false;} Break;case r.id.btnpre://on a btnplayorpause.setbackgroundresource (r.drawable.state_pasue); sendBroadcastToService (Constutil.state_prevIOUS); isplaying=true;break;default:break;}}};/ * * Seekbar Progress Change Event */onseekbarchangelistener schangelistener=new Onseekbarchangelistener () {@Overridepublic void Onsto Ptrackingtouch (SeekBar SeekBar) {//TODO auto-generated method stub//When drag is stopped, Controls mediaPlayer to play the music MusicService.mediaPlayer.seekTo (Seekbar.getprogress ()) at the specified location; Musicservice.ischanging=false; } @Overridepublic void Onstarttrackingtouch (SeekBar SeekBar) {//TODO auto-generated method stubmusicservice.ischanging =true;} @Overridepublic void onprogresschanged (SeekBar SeekBar, int progress,boolean fromuser) {//TODO auto-generated method Stu b}}; @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it I S Present.menu.add (Menu.none, Constutil.menu_about, Menu.none, "about"); Menu.add (Menu.none, Constutil.menu_exit, Menu.none, "exit"); return true;} /** * Back-desk service send control broadcast * @param state int Status Control code * */protected void Sendbroadcasttoservice (int.) {//TODO Auto-gen erated mEthod stubintent intent=new Intent (); intent.setaction (constutil.musicservice_action); Intent.putextra ("Control", State);//the Broadcast Sendbroadcast (intent) that sends playback control to the back desk service;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//TODO auto-generated method Stubswitch (Item.getitemid ( ) {Case ConstUtil.MENU_ABOUT:LayoutInflater inflater=layoutinflater.from (this); LinearLayout layout= (linearlayout) inflater.inflate (r.layout.about, NULL); Alertdialog dialog=new Alertdialog.builder (this). Create ();d ialog.settitle ("about");d Ialog.seticon (r.drawable.ic_ Launcher);d Ialog.setview (layout);d ialog.show (); Break;case ConstUtil.MENU_EXIT:sendBroadcastToService ( Constutil.state_stop); This.finish (); break;default:break;} return true;} Create a broadcast receiver to receive the broadcast class Musicboxreceiver extends broadcastreceiver{@Overridepublic void OnReceive issued by the background service ( Context context, Intent Intent) {//TODO auto-generated method stub//Gets the current message in the Intent, which represents the song currently playing int present = Intent.getintextra ("Current",-1); Title.settext (titlEstrs[current]);//Update Music title Author.settext (Authorstrs[current]);//update Music author}}}

Background service class for music playback:

Musicservice.java

Package Com.jph.musicbox;import Java.io.ioexception;import Java.util.timer;import java.util.timertask;import Com.jph.util.constutil;import Android.app.service;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.content.res.assetfiledescriptor;import Android.content.res.assetmanager;import Android.media.MediaPlayer ; Import Android.media.mediaplayer.oncompletionlistener;import android.os.ibinder;/** * Describe:</br> * </ Br> is responsible for background service * </br>1 music playback. Plays the specified music * </br>2 by receiving a broadcast that controls playback information from the foreground. Load the music * </br>3 under the Assets folder. Create listeners for MediaPlayer events when the current music is playing * </br>, I play the next music * </br>4. Create a timer for each music that is playing, to check playback progress * </br>     and update the progress bar * </br> @author jph * </br>date:2014.08.07 * */public class Musicservice extends Service {Timer mtimer;    TimerTask Mtimertask; The static Boolean ischanging=false;//mutually rejects the variable, preventing the timer from progressing when dragging with seekbar//creating a Media Player object static MediaPlayermediaplayer;//create an object for the asset manager Assetmanager assetmanager;//An array of music names String[]musics=new string[]{" Taoshengyijiu-maoning.mp3 "," Youcaihua-chenglong.mp3 "," You are the One.mp3 "};//current playing music int current=0;//current playback status int state=constutil.state_non;//Record Timer execution status Boolean istimerrunning=false; @Overridepublic void OnCreate () {//TODO Auto-generated method Stubsuper.oncreate ();//Register receiver Musicserciereceiver receiver=new musicserciereceiver (); Ntentfilter filter=new intentfilter (); filter.addaction (constutil.musicservice_action); RegisterReceiver (receiver, filter); mediaplayer=new mediaPlayer (); Assetmanager=getassets ();// Create listener Mediaplayer.setoncompletionlistener for MediaPlayer completion event (new Oncompletionlistener () {@Overridepublic void Oncompletion (MediaPlayer MP) {//TODO auto-generated method Stub//mtimer.cancel ();//Cancel Timer current++;p Repareandplay ( (current);}}); /** * Load and Play Music * @param index int indices play the first few music indexes * */protected void prepareandplay (int index) {//TODO auto-generated met Hod stubif (istimerrunning) {//Assuming the timer isLine Mtimer.cancel ();//Cancel timer istimerrunning=false;} if (index>2) {current=index=0;} if (index<0) {current=index=2;} Send broadcast stop foreground activity update Interface Intent Intent=new Intent () Intent.putextra ("current", index); Intent.setaction ( constutil.musicbox_action); Sendbroadcast (intent); try {// Gets the Assetfiledescriptor object for the specified file under the Assets folder Assetfiledescriptor ASSETFILEDESCRIPTOR=ASSETMANAGER.OPENFD (musics[ Current]); Mediaplayer.reset ();//Initialize MediaPlayer object Mediaplayer.setdatasource (  Assetfiledescriptor.getfiledescriptor (), Assetfiledescriptor.getstartoffset (), assetfiledescriptor.getlength ()); Prepare to play Music mediaplayer.prepare ();//Play Music Mediaplayer.start ();//getduration () method after the prepare () method, otherwise attempt to call will appear Getduration without a valid MediaPlayer exception MusicBox.skbMusic.setMax (Mediaplayer.getduration ());//Set Seekbar length} catch ( IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}        ----------Timer record Playback progress---------//Mtimer = new timer (); Mtimertask = new TimerTask () {@Override public VOID Run () {istimerrunning=true;                  if (ischanging==true)//The progress of the progress bar is not processed when the user is dragging the progress bar, return;            MusicBox.skbMusic.setProgress (Mediaplayer.getcurrentposition ());         }        };       Check the playback progress Mtimer.schedule every 10 milliseconds (mtimertask, 0, 10); } @Overridepublic ibinder Onbind (Intent Intent) {//TODO auto-generated method Stubreturn null;} Create a broadcast receiver for receiving foreground activity the broadcast class Musicserciereceiver extends broadcastreceiver{@Overridepublic void OnReceive ( Context context, Intent Intent) {//TODO auto-generated method Stubint Control=intent.getintextra ("Control",-1); switch ( Control) {Case constutil.state_play://play music if (state==constutil.state_pause) {//Assuming the original state is paused Mediaplayer.start ();} else if (state!=constutil.state_play) {prepareandplay (current);} State=constutil.state_play;break;case constutil.state_pause://Pause Play if (State==constutil.state_play) { Mediaplayer.pause (); state=constutil.state_pause;} Break;case constutil.state_stop://Stop Play IF (state==constutil.state_play| | State==constutil.state_pause) {mediaplayer.stop (); state=constutil.state_stop;} Break;case constutil.state_previous://on a prepareandplay (--current); state=constutil.state_play;break;case constutil.state_next://next Prepareandplay (++current); state=constutil.state_play;break;default:break;}}}
constant Tool Class (Constutil.java):

package com.jph.util;/** * describe:</br> * </br> Constants Tool class * </br> constants used primarily for other class providers * </br> @author JPH * < /br>date:2014.08.07 * */public class Constutil {//musicbox receiver can respond to actionpublic static final String musicbox_action= "Com.jph.musicbox.MUSICBOX_ACTION"; the Actionpublic static final String musicservice_action= that the//musicservice receiver can respond to " Com.jph.musicbox.MUSICSERVICE_ACTION ";//Initialize flagpublic static final int state_non=0x122;//play flagpublic static final int state_play=0x123;//paused flagpublic static final int state_pause=0x124;//stop put flagpublic static final int state_stop= 0x125;//play the previous flagpublic static final int state_previous=0x126;//play the next flagpublic static final int state_next=0x127;// Menu about option itemidpublic Static final int menu_about=0x200;//Menu exit selected item itemidpublic static final int menu_exit=0x201;public Constutil () {//TODO auto-generated constructor stub}} 
Project manifest profile: Androidmanifest.xml:
<?

XML version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.jph.musicbox" android:versioncode= "1" android:versionname= "1.0" > <uses-sdk android:min sdkversion= "8" android:targetsdkversion= "/>" <application android:allowbackup= "true" Android oid:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <!--remove the title bar of the main interface--<activity android:name= "Com.jph.musicbox.MusicBox" Android:labe L= "@string/app_name" Android:theme= "@android: Style/theme.black.notitlebar" > <intent-filter&gt ; <action android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.catego Ry. LAUNCHER "/> </intent-filter> </activity> <!--Musicservice and &lt ; Service andRoid:name= "Com.jph.musicbox.MusicService" ></service> </application></manifest>






Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Android based on development service music player

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.