Simple music player

Source: Internet
Author: User

interface, the use of service services to build, to achieve background playback. Includes play, pause, replay, stop function

Let's take a look at its implementation (there are audio files in the path). 1. The interface layout does not introduce 2.service code
 Public classPlayerserviceextendsService {PrivateMediaPlayer player; @Override Public voidonCreate () {Super. OnCreate (); Log. I ("", "OnCreate" ); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {Log. I ("", "Onstartcommand" ); return Super. Onstartcommand (Intent, flags, Startid); }          /*** This method is executed when the activity binds the service, returning the IBinder implementation (personal understanding, equivalent to the medium between components)*/@Override Publicibinder onbind (Intent Intent) {Log. I ("", "Onbind" ); return NewPlayerbinder (); }          /*** Implements player is used because if Playerbinder expands external functionality, it does not affect the player's call, enabling decoupling*/     Private classPlayerbinderextendsBinderImplementsplayer{@Override Public BooleanPlay (String path) {Booleanresult =false; Try{player=NewMediaPlayer (); Player.setaudiostreamtype (Audiomanager.                      Stream_music);                      Player.setdatasource (path);                      Player.prepare ();                     Player.start (); Result=true; } Catch(Exception e) {//illegalargumentexception, SecurityException, IllegalStateException, IOException (simplified processing)                      return false; }                 returnresult; }             //play, pause toggle@Override Publicstring SwitchState (String path) {string result= ""; if(player==NULL){                      if(play (path)) {result= "Paused"; } Else{result= "Play"; }                } Else if(Player.isplaying ()) {player.pause (); Result= "Play"; } Else{Player.start (); Result= "Paused"; }                 returnresult; } @Override PublicString Replay () {string result= ""; if(player!=NULL) {Player.seekto (0);                     Player.start (); Result= "Paused"; }                 returnresult; } @Override Publicstring Stop () {string result= ""; if(player!=NULL) {player.stop ();                      Player.release (); Player=NULL; Result= "Play"; }                 returnresult; } @Override Publicstring Getplayerstate () {string result= ""; if(player!=NULL&&player.isplaying ()) {Result= "Paused"; }                 returnresult; }} @Override Public voidOnDestroy () {Super. OnDestroy (); Log. I ("Service", "Ondestory" ); }}

Interface File
 Public Interface Player {           publicboolean  play (String path);        Public string SwitchState (string path);        Public String Replay ();        Public String Stop ();        Public String getplayerstate ();}

 3. Finally paste the activity code 
 Public classMainactivityextendsActivityImplementsOnclicklistener {PrivatePlayer Playerinter; PrivateEditText Etmainpath; PrivatePlayerconnection conn =Newplayerconnection (); PrivateButton Btmainplaypause, Btmainreplay, btmainstop; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);            Setcontentview (r.layout. Activity_main); Etmainpath=(EditText) Findviewbyid (R.id.et_main_path); Btmainplaypause=(Button) Findviewbyid (r.id.bt_mian_play_pause); Btmainreplay=(Button) Findviewbyid (R.id.bt_mian_replay); Btmainstop=(Button) Findviewbyid (r.id.bt_mian_stop); Btmainplaypause.setonclicklistener ( This); Btmainreplay.setonclicklistener ( This); Btmainstop.setonclicklistener ( This); //The service can only be created once, and once the activity is destroyed, creating the activity again will not recreate the serviceIntent startintent =NewIntent ( This, Playerservice.class );            StartService (startintent); Intent bindintent=NewIntent ( This, Playerservice.class );     Bindservice (Bindintent, Conn, bind_auto_create); }       Private classPlayerconnectionImplementsserviceconnection {//execute this method when the connection is successful, get the player operator interface@Override Public voidonserviceconnected (componentname name, IBinder service) {Playerinter=(Player) service; String State=playerinter.getplayerstate (); if(!state.equals ("") {btmainplaypause.settext (state); }} @Override Public voidonservicedisconnected (componentname name) {}}//Unbind at each end@Override Public voidFinish () {Super. Finish (); //Unbind the service connection at each end of activityUnbindservice (conn); Log. I ("", "disconnect" ); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { Caser.id. bt_mian_play_pause:string playstate=playerinter.switchstate (Etmainpath.gettext (). toString (). Trim ()); if(!playstate.equals ("") {btmainplaypause.settext (playstate); }                  Break;  Caser.id. bt_mian_replay:string replaystate=Playerinter.replay (); if(!replaystate.equals ("") {btmainplaypause.settext (replaystate); }                  Break;  Caser.id. bt_mian_stop:string stopstate=Playerinter.stop (); if(!stopstate.equals ("") {btmainplaypause.settext (stopstate); }                  Break; default:                  Break; }} @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Log. I ("Activity", "ondestory" ); } }

Simple 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.