Android uses service to play music

Source: Internet
Author: User

Like music this time-consuming and appropriate background operation should be placed in the service to operate, rather than in the activity, the following describes the use of the service music player

First create a Musicservice

The Declaration of service changes is automatically generated in the configuration manifest

Java code in Musicservice, which contains music-related operations

 Public classMusicserviceextendsService {PrivateString Path = "Mnt/sdcard/123.mp3"; PrivateMediaPlayer player; @Override Publicibinder onbind (Intent Intent) {//when the OnCreate is executed, the Onbind will be executed to return the method of manipulating the song.        return NewMybinder (); } @Override Public voidonCreate () {Super. OnCreate (); //This is done only once to prepare the playerPlayer =NewMediaPlayer (); Try{player.setdatasource (path); //Preparing ResourcesPlayer.prepare (); } Catch(IOException e) {e.printstacktrace (); } LOG.E ("Services", "Preparing to play Music"); }    //This method contains actions about the song     Public classMybinderextendsBinder {//determine if the playback state is in play         Public Booleanisplaying () {returnplayer.isplaying (); }        //Play or pause a song         Public voidPlay () {if(Player.isplaying ()) {player.pause (); } Else{Player.start (); } LOG.E ("Services", "playing music"); }        //returns the length of the song, in milliseconds         Public intgetduration () {returnplayer.getduration (); }        //returns the current progress of the song, in milliseconds         Public intgetcurrenpostion () {returnplayer.getcurrentposition (); }        //set the progress of the song playback in milliseconds         Public voidSeekto (intMesc)        {Player.seekto (MESC); }    }}

Only one button and progress bar is added to the layout

    <ButtonAndroid:id= "@+id/play"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Play"Android:text= "Play" />    <SeekBarAndroid:id= "@+id/sb"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" />

Java code in Mainactivity

 Public classMainactivityextendsappcompatactivity {PrivateMyConnection Conn; PrivateMusicservice.mybinder Musiccontrol; PrivateButton playbtn; PrivateSeekBar SeekBar; Private Static Final intupdate_progress = 0; //update progress bar with handler timing    PrivateHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { Caseupdate_progress:updateprogress ();  Break;    }        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); PLAYBTN=(Button) Findviewbyid (R.id.play); SeekBar=(SeekBar) Findviewbyid (R.ID.SB); Intent Intent3=NewIntent ( This, Musicservice.class); Conn=Newmyconnection (); //use a hybrid approach to turn on services,StartService (INTENT3);        Bindservice (INTENT3, Conn, bind_auto_create); Seekbar.setonseekbarchangelistener (NewSeekbar.onseekbarchangelistener () {@Override Public voidOnprogresschanged (SeekBar SeekBar,intProgressBooleanFromuser) {                //Progress bar Change                if(Fromuser) {Musiccontrol.seekto (progress); }} @Override Public voidOnstarttrackingtouch (SeekBar SeekBar) {//start touching the progress bar} @Override Public voidOnstoptrackingtouch (SeekBar SeekBar) {//Stop Touch progress bar            }        }); }    Private classMyConnectionImplementsserviceconnection {//This method is entered when the service is started .@Override Public voidonserviceconnected (componentname name, IBinder service) {//get the Mybinder in the serviceMusiccontrol =(musicservice.mybinder) service; //Update the text of a buttonUpdateplaytext (); //set the maximum value of the progress barSeekbar.setmax (Musiccontrol.getduration ()); //set progress for progress barseekbar.setprogress (Musiccontrol.getcurrenpostion ()); } @Override Public voidonservicedisconnected (componentname name) {}} @Overrideprotected voidOnresume () {Super. Onresume (); //start updating the progress bar after entering the interface        if(Musiccontrol! =NULL) {handler.sendemptymessage (update_progress); }} @Overrideprotected voidOnDestroy () {Super. OnDestroy (); //unbind the service after exiting the appUnbindservice (conn); } @Overrideprotected voidOnStop () {Super. OnStop (); //Stop updating progress bar ProgressHandler.removecallbacksandmessages (NULL); }    //Update progress bar    Private voidupdateprogress () {intCurrenpostion =musiccontrol.getcurrenpostion ();        Seekbar.setprogress (currenpostion); //Update the progress bar every 500 milliseconds using handlerHandler.sendemptymessagedelayed (update_progress, 500); }    //Update the text of a button     Public voidUpdateplaytext () {if(Musiccontrol.isplaying ()) {Playbtn.settext (Pause);        Handler.sendemptymessage (update_progress); } Else{Playbtn.settext (Player); }    }    //call the Play () method in Mybinder     Public voidPlay (view view) {Musiccontrol.play ();    Updateplaytext (); }}

Android uses service to play music

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.