Android Simple Music Playback instance _android

Source: Internet
Author: User

Service translated into Chinese is the services, familiar with the Windows system students must be very familiar with. The service in Android is similar to the service function in Windows, where an invisible process executes in the background.
Android services, it is different from the activity, it can not interact with the user, can not be started, run in the background of the program, if we quit the application, the service process does not end, it still runs in the background, such as we open a music player to listen to music, Listen to music at the same time also want to do other things, such as online chat q, or online browsing news and other things. In this way, we need to use service services. Here's a simple example of a music player to illustrate the life cycle of the service and the use of the service.
The following is the program structure chart of the music player demo:

The life cycle of the Android service:

The life cycle of a service in Android is not complicated, but it inherits from OnCreate (), OnStart (), Ondestory () three methods. When we first start service services, call the OnCreate ()--> OnStart () Two methods, calling the Ondestory () method when the service is stopped. If the service is already started, the second time you start the same one, it's just the way to call OnStart ().
use of the Android service:
1. Referring to the above program structure diagram, we can create an Android program, create an activity in the SRC directory, a service class that inherits from the Services class, and create a raw folder in the Resource folder res directory to store audio files. If you put the Music.mp3 music file in the directory. The main interface of the program is as follows:

2, the layout directory of the Main.xml file source:

<?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:te 
    Xt= "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 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"; 
   
  Define music player variables private MediaPlayer mPlayer; The service does not exist to be invoked when it needs to be created, regardless of whether startservice () or Bindservice () will invoke the method when it is started @Override public void OnCreate () {Toast.maketext T 
    His, "Musicsevice onCreate ()", Toast.length_short). Show (); 
     
    LOG.E (TAG, "Musicserice onCreate ()"); 
    MPlayer = Mediaplayer.create (Getapplicationcontext (), r.raw.music); 
    Setting can repeat mplayer.setlooping (true); 
  Super.oncreate (); 
        @Override public void OnStart (Intent Intent, int startid) {Toast.maketext (this, Musicsevice OnStart ()) 
    , Toast.length_short). Show (); 
     
    LOG.E (TAG, "Musicserice OnStart ()"); 
     
    Mplayer.start ();Super.onstart (Intent, Startid); @Override public void OnDestroy () {Toast.maketext (this, Musicsevice OnDestroy ()), Toast.length_sh 
    ORT). Show (); 
     
    LOG.E (TAG, "Musicserice OnDestroy ()"); 
     
    Mplayer.stop (); 
  Super.ondestroy (); The method is called @Override public ibinder onbind (Intent Intent) {toast.maketext (TH) when other objects notify the service by Bindservice method 
    IS, "Musicsevice onbind ()", Toast.length_short). Show (); 
     
    LOG.E (TAG, "Musicserice onbind ()"); 
     
    Mplayer.start (); 
  return null; The method is called @Override public boolean onunbind (Intent Intent) {Toast.maketext When other objects notify the service through the Unbindservice method) 
    (This, "Musicsevice onunbind ()", Toast.length_short). Show (); 
     
    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 String tag = "Musicservice"; /** called the activity is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.main); 
    Output Toast messages and log records Toast.maketext (this, "musicserviceactivity", Toast.length_short). Show (); 
     
    LOG.E (TAG, "musicserviceactivity"); 
  Initlizeviews (); private void Initlizeviews () {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) {  
        Displays the object specified Intent is a 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://Stop Service StopService (intent); 
        Break 
          Case R.id.bindmusic://Binding service Bindservice (intent, Conn, context.bind_auto_create); 
        Break 
          Case R.id.unbindmusic://Untied Service Unbindservice (conn); 
        Break 
     
     } 
      } 
    }; Binding fixed-point hit Monitor Btnstart.setonclicklisTener (OCL); 
    Btnstop.setonclicklistener (OCL); 
    Btnbind.setonclicklistener (OCL); 
  Btnunbind.setonclicklistener (OCL); }//Define Service link Object final serviceconnection conn = new Serviceconnection () {@Override public void Onse rvicedisconnected (componentname name) {Toast.maketext (musicserviceactivity.this, musicserviceactivity OnSeviceDis 
      Connected ", Toast.length_short). Show (); 
    LOG.E (TAG, "musicserviceactivity onsevicedisconnected"); @Override public void onserviceconnected (componentname name, IBinder service) {Toast.maketext (Mu 
      Sicserviceactivity.this, "Musicserviceactivity onserviceconnected", Toast.length_short). Show (); 
    LOG.E (TAG, "musicserviceactivity onserviceconnected"); 
} 
  }; 
 }

5. Finally, we should not forget to add the service registration to the Androidmanifest.xml configuration file. That is, add <service android:name= to the application node . Musicservice "/> for registration.
6. Let's look at the service lifecycle shown in the LOG.E after the program runs

7, we in the Android terminal equipment to see the music played just started the service, see we quit the program after the program is not the service is still running it? Follow the steps below:Menu--> Settings--> applications--> Running Services . You can see which services are running in the pop-up Running service.

So we see we quit the program, because the service is still running in the background, so our music can continue to play. In this way, we can enjoy the music, while chatting QQ, or browsing the news and so on.

Related Article

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.