Android uses service for music playback

Source: Internet
Author: User

today's player takes advantage of the service, plays music on the service side, the progress bar on the activity side, so the main work is activity and service interaction, this article will use IBinder to interact, mainly activity can invoke the service's function , you can refer to my blog post .

key points in this article: using IBinder to implement activity-controlled service

Implementation features:

1 Controlling playback progress:

The activity invokes the service's function to control the MediaPlayer. including playback at startup and sliding Seekbar, the MediaPlayer is set up to control playback progress.

2 Play Progress Update:

in the activity to open multi-threading, background every 100ms send a message, in the UI thread using handler to determine the message, then the activity Call service function, get playback progress (percentage), Update the Seekbar progress bar in time.

As follows:


The layout is simple, as shown below:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <textview android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "pla Y "/> <button android:id=" @+id/playbutton "android:layout_width=" Wrap_content "android:layout_height = "Wrap_content" android:text= "Play"/><button android:id= "@+id/pausebutton" android:layout_width= "Wrap_co         Ntent "android:layout_height=" wrap_content "android:text=" pause "/> <seekbar android:id=" @+id/seekbar " Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_marginleft= "2 0DP "android:layout_marginright=" 20DP "android:max=" android:progress= "ten"/></linea Rlayout>
The activity code is as follows:

<pre name= "code" class= "Java" >public class Mainactivity extends Activity {Boolean mbound = false; Musicservice Mservice; SeekBar seekbar;//Multi-threading, background update uithread mythread;//control Background Thread Exit Boolean playstatus = true;//process progress bar update Handler Mhandler = new Handler () {@Override public void Handlemessage (Message msg) {switch (msg.what) {case 0://gets the progress from the bundle, is the double type, the percentage played Dou              ble progress = Msg.getdata (). GetDouble ("Progress");//Depending on the playback percentage, calculate the actual position of SeekBar int max = Seekbar.getmax ();                        int position = (int) (max*progress);              Set the actual position of the SeekBar seekbar.setprogress (position);        Break                    Default:break;} }}; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);//define a new thread to send a message informing update uimythread = new Thread (new MyThread ());//Binding Service;intent Serviceintent = new Intent (this, musicservice.class);//If Unbound, bind if (!mbound) {Bindservice (serviceiNtent, Mconnection, context.bind_auto_create);} Initialize the play button PlayButton = (button) Findviewbyid (R.id.playbutton);p Laybutton.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method stubif (mbound) {Mservice.play ( );}}});/ /Initialize pause button Pausebutton = (button) Findviewbyid (R.id.pausebutton);p Ausebutton.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method stub//first needs to determine the binding condition if (mbound) {    Mservice.pause ();}}); SeekBar = (SeekBar) Findviewbyid (R.id.seekbar); Seekbar.setonseekbarchangelistener (new Seekbar.onseekbarchangelistener () {@Overridepublic void Onstoptrackingtouch (SeekBar SeekBar) {//Manually adjust progress//TODO Auto-generated method Stub//seekbar The drag position int dest = seekbar.getprogress ();//seekbar max value int max = Seekbar.getmax ();// Call service to adjust playback progress mservice.setprogress (max, dest);} @Overridepublic void onprogresschanged (SeekBar arg0, int arg1, Boolean arg2) {//TODO auto-generated method stub} @Override Public void Onstarttrackingtouch (SeekBar arg0) {//TODO auto-generated Method stub}}); Implement Runnable interface, multithreading real-time update progress bar public class MyThread implements runnable{//Notify UI update message//The value used to pass progress to the UI thread bundle data = new Bundle ( )///update UI interval time int milliseconds = 100;double progress; @Overridepublic void Run () {//TODO auto-generated method stub//to identify whether                                        Also in playback state, used to control thread exit while (Playstatus) {try {///bind succeeded to start updating UI if (Mbound) {                    Send a message asking for update UI message msg = new Message ();                                 Data.clear ();            progress = mservice.getprogress ();                        Msg.what = 0;            Data.putdouble ("Progress", progress);            Msg.setdata (data);                    Mhandler.sendmessage (msg);          } thread.sleep (milliseconds);  Thread.CurrentThread (). Sleep (milliseconds); Update UI} catch every 100ms (InterrupTedexception e) {//TODO auto-generated catch block E.printstacktrace (); }}}}/** defines callbacks for service binding, passed to Bindservice () */private Serviceconnection MC onnection = new Serviceconnection () {@Override public void onserviceconnected (ComponentName className , IBinder Binder) {//We ' ve bound to LocalService, cast the IBinder and get LocalService in                    Stance Mybinder Mybinder = (mybinder) binder;                          Get Service Mservice = (musicservice) mybinder.getservice ();                          Bind succeeded Mbound = true;        Open thread, update UI Mythread.start ();          } @Override public void onservicedisconnected (ComponentName arg0) {mbound = false;     }      }; @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to theAction Bar If it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic void OnDestroy () {//Destroy the activity, remember to destroy the thread playstatus = False;super.ondestroy ();}}


The service code is as follows:

public class Musicservice extends Service {ibinder musicbinder = new Mybinder ();//Get Activity handler to notify update progress bar handler M Handler;        Media class that plays music MediaPlayer mediaplayer;//The path of the local song String path = "/storage/sdcard1/music/Romantic Full House. mp3";          Private String TAG = "MyService"; @Override public void OnCreate () {super.oncreate ();                  LOG.D (TAG, "onCreate () executed");            Init (); } @Overridepublic ibinder Onbind (Intent arg0) {//TODO auto-generated Method Stub//When Bound, returns a Musicbinderreturn music Binder;} Class Mybinder extends Binder{public Service getService () {return musicservice.this;}}    Initialize music to play void Init () {//Enter Idlemediaplayer = new MediaPlayer (); try {//Initialize Mediaplayer.setdatasource (path);  Mediaplayer.setaudiostreamtype (Audiomanager.stream_music); Prepare loads the media resources asynchronously Mediaplayer.prepareasync ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Returns the current playback progress, which is a double type, which is the percentage played public double getprogress () {int position = MedIaplayer.getcurrentposition ();                  int time = Mediaplayer.getduration ();                Double progress = (double) position/(double) time;  return progress; }//play progress via activity public void setprogress (int max, int dest) {int time = Mediaplayer.getduration (); Mediaplayer.seekto ( Time*dest/max);} Test play Music public void play () {if (MediaPlayer! = null) {Mediaplayer.start ();}} Pause Music public void pause () {if (MediaPlayer! = null && mediaplayer.isplaying ()) {Med          Iaplayer.pause (); }}//service destroy, stop playing music, release resources @Override public void OnDestroy () {//Recycle resources at end of activity if (MEDIAPLA         Yer! = null && mediaplayer.isplaying ()) {mediaplayer.stop ();         Mediaplayer.release ();     MediaPlayer = null;     } Super.ondestroy (); }}

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.