Service-based music player

Source: Internet
Author: User

This is a service-based music player. The program's music will be played by the background service component. When the background playing status changes, the program sends a broadcast notification to the foreground activity update interface. When you click the foreground activity interface button or drag the progress bar, the system sends a broadcast notification to the background service to change the playing status and play the specified music.

Program running:



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 and Roid. 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 broadcaster * </BR> This application mainly implements: * </BR> 1. play-related control information is sent through the foreground activity and transmitted to the background service in the form of broadcast * </BR>. The background service is responsible for playing music. * </BR> receives background broadcasts to update the song and singer names on the playback interface. * </BR> 2. the progress bar is used to display the current playback position. When you drag the progress bar, * </BR> controls the playing of music at the specified position through the onseekbarchangelistener event * </BR> mediaplayer in the background. * </BR> @ author jph * </BR> date: 2014.08.07 **/public class musicbox extends activity {imagebutton btnplayorpause, btnpre, btnnext; // progress bar static seekbar skbmusic; // obtain the title, text box textview title, and author; string [] titlestrs = new string [] {"taosheng still", "Rape flower ", "You are the one"}; string [] authorstrs = new string [] {"Mao Ning", "Jackie Chan", "unknown artist "}; // Boolean isplaying = false; @ overrideprotected void oncreate (bundl E 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. seton Clicklistener (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 the receiver musicboxreceiver mreceiver = new musicboxreceiver (); intentfilter filter = new intentfilter (); filter. addaction (constutil. musicbox_action); registerreceiver (mreceiver, filter); // start backend serviceintent I Ntent = new intent (this, musicservice. class); startservice (intent);} onclicklistener listener = new onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubswitch (v. GETID () {case R. id. btnnext: // The 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: // The Last 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 onstoptrackingtouch (seekbar) {// todo auto-generated method stub // After the drag is stopped, control the mediaplayer to play music musicservice at the specified position. mediaplayer. seekto (seekbar. getprogress (); musicservice. ischanging = false ;}@ overridepublic void onstarttrackingtouch (seekbar) {// todo auto-generated method stubmusicservice. ischanging = true;} @ overridepublic void onprogresschanged (seekbar, int progress, Boolean fromuser) {// todo auto-generated method stub}; @ overridepublic Boolean oncreateoptionsmenu (menu) {// inflate the menu; this adds items to the action bar if it is present. menu. add (menu. none, constutil. menu_about, menu. none, "about"); menu. add (menu. none, constutil. menu_exit, menu. none, "exit"); Return true;}/*** send control broadcast to backend Service * @ Param state int state control status code **/protected void sendbroadcasttoservice (INT state) {// todo auto-generated method stubintent intent = new intent (); intent. setaction (constutil. musicservice_action); intent. putextra ("control", State); // send the broadcast sendbroadcast (intent) ;}@ overridepublic Boolean onoptionsitemselected (menuitem item) of the playback control to the background service) {// 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 (); dialog. settitle ("about"); dialog. seticon (R. drawable. ic_launcher); dialog. setview (layout); dialog. 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 (context, intent) sent by the background service) {// todo auto-generated method stub // gets the current message in the intent. Current indicates the currently playing song int current = intent. getintextra ("current",-1); title. settext (titlestrs [current]); // update the music Title Author. settext (authorstrs [current]); // updated by music author }}}
Background services 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. me Dia. mediaplayer; import android. media. mediaplayer. oncompletionlistener; import android. OS. ibinder;/*** describe: </BR> * </BR> background service responsible for music playback * </BR> 1. you can play a specified music by receiving a broadcast from the foreground that controls the playback information. * </BR> 2. load music in the Assets Directory * </BR> 3. creates a listener for the mediaplayer completion event. When the current music is played * </BR>, the listener automatically plays the next music * </BR> 4. create a timer for each playing music to detect the playing progress * </BR> and update the progress bar * </BR> @ author jph * </BR> date: 2014.08.07 **/public class musicservice extends Service {T Extends mtimer; timertask mtimertask; static Boolean ischanging = false; // mutex variable to prevent degree conflicts when the timer and seekbar are dragged // create a media player object static mediaplayer; // create an asset manager object assetmanager; // an array that stores the music name string [] musics = new string [] {"taoshengyijiu-maoning.mp3", "youcaihua-chenglong.mp3 ", "You are the oneplay"}; // The current playing music int current = 0; // The current playing status int state = constutil. state_non; // record the timer running status Boolean istimerrunning = fa LSE; @ overridepublic void oncreate () {// todo auto-generated method stubsuper. oncreate (); // register the receiver musicserciereceiver receiver = new musicserciereceiver (); intentfilter filter = new intentfilter (); filter. addaction (constutil. musicservice_action); registerreceiver (receiver, filter); mediaplayer = new mediaplayer (); assetmanager = getassets (); // creates a listener for the mediaplayer completion event. setoncompletionlistener (New oncomplet Ionlistener () {@ overridepublic void oncompletion (mediaplayer MP) {// todo auto-generated method stub // mtimer. cancel (); // cancel the timer current ++; prepareandplay (current );}});} /*** load and play music ** @ Param index int index the index of the first music to play **/protected void prepareandplay (INT index) {// todo auto-generated method stubif (istimerrunning) {// If timer is running mtimer. cancel (); // cancel the timer istimerrunning = false;} If (index> 2) {current = index = 0;} If (index <0) {current = Index = 2;} // send broadcast stop foreground activity update interface intent = new intent (); intent. putextra ("current", index); intent. setaction (constutil. musicbox_action); sendbroadcast (intent); try {// obtain the assetfiledescriptor object assetfiledescriptor = assetmanager of the specified file in the Assets Directory. openfd (musics [current]); mediaplayer. reset (); // initialize the mediaplayer object mediaplayer. setdatasource (assetfiledescriptor. getfiledesc Riptor (), assetfiledescriptor. getstartoffset (), assetfiledescriptor. getlength (); // prepare to play the music mediaplayer. prepare (); // play the music mediaplayer. start (); // The getduration () method must be followed by the prepare () method. Otherwise, the attempt to call getduration without a valid mediaplayer exception musicbox will occur. skbmusic. setmax (mediaplayer. getduration (); // set the seekbar length} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} // ---------- the timer records the playback progress --------- // Mtimer = new timer (); mtimertask = new timertask () {@ override public void run () {istimerrunning = true; If (ischanging = true) // when the user is dragging the progress bar, the return; musicbox. skbmusic. setprogress (mediaplayer. getcurrentposition () ;}}; // checks the playback progress of mtimer every 10 milliseconds. schedule (mtimertask, 0, 10) ;}@ overridepublic ibinder onbind (intent) {// todo auto-generated method stubreturn NULL;} // create a broadcast receiver for receiving Receive broadcast class musicserciereceiver extends broadcastreceiver {@ overridepublic void onreceive (context, intent) sent by the front-end activity {// todo auto-generated method stubint control = intent. getintextra ("control",-1); Switch (Control) {Case constutil. state_play: // play the music if (State = constutil. state_pause) {// if the original status is paused mediaplayer. start ();} else if (State! = Constutil. state_play) {prepareandplay (current);} state = constutil. state_play; break; Case constutil. state_pause: // pause if (State = constutil. state_play) {mediaplayer. pause (); State = constutil. state_pause;} break; Case constutil. state_stop: // stop playing if (State = constutil. state_play | state = constutil. state_pause) {mediaplayer. stop (); State = constutil. state_stop;} break; Case constutil. state_previous: // prepareandplay (-- current); State = constutil. state_play; break; Case constutil. state_next: // The next prepareandplay (++ current); State = constutil. state_play; break; default: break ;}}}}
Constant tool class (constutil. Java ):

Package COM. jph. util;/*** describe: </BR> * </BR> constant tool class * </BR> is mainly used for constants used by other class providers * </BR> @ author jph * </BR> date: 2014.08.07 **/public class constutil {// actionpublic static final string musicbox_action = "com. jph. musicbox. musicbox_action "; // actionpublic static final string musicservice_action =" com. jph. musicbox. musicservice_action "; // initialize flagpublic static final int state_non = 0x122; // flagpublic static final int state_play = 0x123; // pause the flagpublic static final int state_pause = 0x124; // stop the flagpublic static final int state_stop = 0x125; // flagpublic static final int state_previous = 0x126; // flagpublic static final int state_next = 0x127; // menu itemidpublic static final int menu_about = 0x200; // The itemidpublic static final int menu_exit = 0x201; Public constutil () {// todo auto-generated constructor stub }}
Configuration File: 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: minsdkversion =" 8 "Android: targetsdkversion = "18"/> <application Android: allowbackup = "true" Android: 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: Label =" @ string/app_name "Android: theme =" @ Android: style/theme. black. notitlebar "> <intent-filter> <action Android: Name =" android. intent. action. main "/> <category Android: Name =" android. intent. category. launcher "/> </intent-filter> </activity> <! -- Register musicservice --> <service android: Name = "com. jph. musicbox. musicservice"> </service> </Application> </manifest>





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.