[Android app] music player

Source: Internet
Author: User

The service is an invisible process that executes in the background .

Android service, it is different from the activity, it is unable to interact with the user , can not start their own , running in the background of the program, if we quit the application, theservice process does not end , It is still running in the background, for example, we open a music player to listen to music, while listening to music, but also want to do other things, such as Internet chat Q, or surf the internet to browse the news and other things. In that case, we need to use the service. Below we use an example of a simple music player to illustrate the life cycle and service usage of the service.

Here is the program structure diagram of the music player demo:

Life cycle of Android Service:

The life cycle of the service in Android is not very complex, but inherits the OnCreate (), OnStart (), Ondestory () three methods . When we first start the service, call OnCreate ()---OnStart () Two methods, and when the service is stopped , call the Ondestory () method. If the service is already started, the second time you start the same one, it just calls the OnStart () method.

Use of Android Service:

[1] Referring to the above program structure diagram, we can create an Android program, in the SRC directory to create an activity, a service class inherited from the services classes, and in the Resource folder res directory to create a raw folder to hold audio files , such as placing Music.mp3 music files in this directory. The main interface of the program is as follows:

[2] The source code of the Main.xml file in the layout directory:

 <?xml version= "1.0"  encoding= "Utf-8"?> <linearlayout xmlns:android= "http// Schemas.android.com/apk/res/android "    android:orientation=" vertical "     android:layout_width= "Fill_parent"     android:layout_height= "Fill_parent"      >     <textview        android: Layout_width= "Fill_parent"        android:layout_height= "Wrap_content"         android:text= "Welcome to andy ' s blog!"         android:textsize= "16sp"/>     <textview         android:layout_width= "Fill_parent"        android: layout_height= "Wrap_content"        android:text= "Music playback service"/>      <button &NBSp;      android:id= "@+id/startmusic"         Android:layout_width= "Wrap_content"        android:layout_height= "Wrap_ Content "       android:text=" Open music playback service/>     < Button        android:id= "@+id/stopmusic"         android:layout_width= "Wrap_content"        android:layout_height = "Wrap_content"        android:text= "Stop music playback service"/>    < Button       android:id= "@+id/bindmusic"        Android:layout_width= "Wrap_content"       android:layout_height= "Wrap_content"       android:text= "Binding music playback Service"/>    <button        andRoid:id= "@+id/unbindmusic"       android:layout_width= "Wrap_content"        android:layout_height= "Wrap_content"       android:text= "  Unbind  --Music playback service/> </LinearLayout>

[3] src directory under musicservice. Java Source code:

 package com.andyidea.service; import android.app.service; import android.content.intent; import android.media.mediaplayer; import android.os.ibinder; import android.util.log; import android.widget.toast; public class musicservice extends service {    //set label for log tool      private static String TAG =  "Musicservice";     //defining music player variables     private MediaPlayer mPlayer;     //The service does not exist to be called when it needs to be created, regardless of whether startservice () or Bindservice () is started, the method is called     @ Override     public void oncreate ()  {         toast.maketext (this,  "musicsevice oncreate ()"                  , toast.length_short). Show ();        &nbsP LOG.E (tag,  "musicserice oncreate ()");         mplayer = mediaplayer.create (GetApplicationContext () ,  r.raw.music);         //settings can be played repeatedly          Mplayer.setlooping (TRUE);         super.oncreate (); &NBSP;&NBSP;&NBSP;&NBSP,}      @Override     public void  OnStart (Intent intent, int startid)  {         Toast.maketext (this,  "Musicsevice onstart ()"                  , toast.length_short). Show (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (tag,  "Musicserice onstart ()");         mplayer.start ();         super.onstart (Intent, startid); &NBSP;&NBSP;&NBSP;&NBSP,}      @Override     public void  OnDestroy ()  {        toast.maketext (this,  "MusicSevice  OnDestroy () "&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;  toast.length_short). Show (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (tag,  "Musicserice ondestroy ()");         mplayer.stop ();         super.ondestroy ();     }     //the method is called when the other object notifies the service through the bindservice  method       @Override     public ibinder onbind (intent intent)  {         toast.maketext (this,  "Musicsevice onbind ()"              &nBsp;   , toast.length_short). Show (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (tag,  "Musicserice onbind ()");         mplayer.start ();         return null;     }     //the method is called when the other object notifies the service through the Unbindservice method       @Override     public boolean onunbind (intent intent)  {         toast.maketext (this,  "Musicsevice onunbind ()"                  , toast.length_short) . Show (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (tag,  "Musicserice onunbind ()");         mplayer.stop ();         return super.onunbind (Intent);      }}

[4] src directory under musicserviceactivity source code:

Package com.andyidea.service; Import android.app.Activity; Import Android.content.ComponentName; Import Android.content.Context; Import android.content.Intent; Import android.content.ServiceConnection; Import Android.os.Bundle; Import Android.os.IBinder; Import Android.util.Log; Import Android.view.View; Import Android.view.View.OnClickListener; Import Android.widget.Button; Import Android.widget.Toast; public class Musicserviceactivity extends Activity {//Set label for log tool private static StringTAG= "Leemusicservice";         @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);         Setcontentview (R.layout.leemainmain);         Output Toast messages and logging Toast.maketext (this, "musicserviceactivity", Toast.length_short). Show (); LOG.E (TAG, "musicserviceactivity");initlizeviews (); } private voidinitlizeviews() {        Button btnStart =  (Button) Findviewbyid ( R.id.startmusic);         Button btnStop =  (Button) Findviewbyid ( R.id.stopmusic);         Button btnBind =  (Button) Findviewbyid ( R.id.bindmusic);         Button btnUnbind =  (Button) Findviewbyid ( R.id.unbindmusic);         //Definition Click Listener          Onclicklistener ocl = new onclicklistener ()  {              @Override              public void onclick (view v)  {                 //shows that the object specified by   intent is a  &nbsP; service                  intent intent = new intent (Musicserviceactivity.this,musicservice.class);                 switch (v.getId ()) {                case  R.id.startmusic:                      //Start Service                      startservice (Intent);                      break;                 case  R.id.stopmusic: &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;             //Stop Service                       StopService (Intent);                      break;                 case  R.id.bindmusic:                      //Binding Service                      bindservice (intent, conn, context.bind_auto_create);                      break;                 case r.id.unbindmusic:                      //Unbind Service                      unbindservice (conn);                      break;                 }              }         } ;          //binding Sentinel Tap monitoring          Btnstart.setonclicklistener (OCL);         btnstop.setonclicklistener (OCL);         btnbind.setonclicklistener (OCL);          btnunbind.setonclicklistener (OCL);     }     //define service link Object     final  Serviceconnection conn = new serviceconnection ()  {          @Override         public void  Onservicedisconnected (componentname name)  {             toast.maketext (musicserviceactivity.this,  "musicserviceactivity  Onsevicedisconnected "                     , toast.length_short). Show (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (TAG,  "MusicServiceActivity  onsevicedisconnected "); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP,}          @Override     &nbsP;   public void onserviceconnected (componentname name, ibinder  Service)  {            toast.maketext ( musicserviceactivity.this,  "musicserviceactivity onserviceconnected"                      ,toast.length_short) . Show (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (TAG,  "MusicServiceActivity  onserviceconnected ");         }     };  }

[5] Finally, let's not forget to add a registration for the service in the Androidmanifest.xml configuration file. That is, add the application node

<service android:name= ". Musicservice "/> To register.

[6] Let's look at the service life cycle shown in LOG.E after the program runs

[7] We look at the music playback service that we just started in the Android terminal, and see if we are still running the program after exiting the program? Follow these steps: Menu---Settings--and applications-Running services. You can see which services are running in the popup Running services.

So we can see that we're out of the program, because the service is still running in the background, so our music will continue to play. In this way, we can enjoy music, while chatting QQ, or browse the news and so on.

Note: Specific code can be downloaded: Musicplayerthroughservice code

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.