Android service detailed and sample code _android

Source: Internet
Author: User

Android Service Details:

1, the concept of service

2, Service life cycle

3, Example: Control the Music broadcast service

First, the concept of service

Service is one of the four basic components of the Android program, and it is a subclass of the context like activity, except that it has no UI interface and is a running component in the background.

Second, the service life cycle

Service objects cannot be started by themselves and need to be started by an activity, service, or other context object. There are two ways to start, Context.startservice and Context.bindservice (). The lifecycle of the two ways is different, as shown in the following example.

Life cycle of the Context.startservice way:

At startup,startservice–> OnCreate () –> OnStart ()
,stopservice–> OnDestroy at Stop ()

Life cycle of the Context.bindservice way:

Binding timing, Bindservice-> onCreate () –> onbind ()
Unbindservice–>onunbind () –> ondestory () when the binding is untied

Iii. Example: Controlling the service of music playback

Below we use a control in the background to play music example to demonstrate what we have just learned, students can see through this example can be clearly seen through the binding of the service after the binding object was destroyed also destroyed.

The following code is shared as follows:

1. Create a new project name lesson14_helloservice,activity named Mainhelloservice.java

2, Res/layout/main.xml in the code written

< 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= "Music playback Service" Android:textsize= "25SP" android:layout_margintop= "10DP" > <button android:text= "Open music playback Service" android:textsize= " 20sp "android:id=" @+id/button01 "android:layout_width=" Wrap_content "android:layout_height=" Android: layout_margintop= "10DP" > </button> <button android:text= "Stop music playback Service" android:textsize= "20SP" android:id= " @+id/button02 "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_margintop=" "10DP" > </button> <button android:text= "Bound music playback Service" android:textsize= "20SP" android:id= "@+id/button03" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_margintop= "10DP" > </button> <button android:text= "Unbind music playback Service" android:textsize= "20SP" android:id= "@+id/button04"
"Android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:layout_margintop=" 10DP ">
 </button> </textview></linearlayout>

3, create a raw directory in the Res directory, and a music file Babayetu.mp3 copy in 3, in the same directory of activity to create a new service file

Musicservice.java

Package android.basic.lesson14;
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 {//label String tag = "Musicservice" for the log tool;

    Defines the music player variable MediaPlayer mPlayer; When other objects notify the service through the Bindservice method, the method is invoked @Override public ibinder onbind (Intent Intent) {toast.maketext (th
        IS, "Musicservice onbind ()", Toast.length_short). Show ();
        LOG.I (Tag, "Musicservice Onbind ()");
        Mplayer.start ();
    return null; The method is invoked @Override public boolean onunbind (Intent Intent) {TOAST.M When the service is notified by the Unbindservice method)
        Aketext (This, "Musicservice onunbind ()", Toast.length_short). Show ();
        LOG.I (Tag, "Musicservice Onunbind ()");
        Mplayer.stop ();
    return false; The service does not exist when it needs to be created, regardless of whether startservice () or Bindservice () will call the method at startup @Override public void OnCreate () {Toast.maketext (this, Musicservice onCreate (), Toast.length_short). Show ();
        Create a music player object Mplayer=mediaplayer.create (Getapplicationcontext (), R.raw.babayetu);
        Setting can repeat mplayer.setlooping (true);
    LOG.I (Tag, "Musicservice onCreate ()");
        When the service is invoked with the StartService method, the modification method @Override public void OnStart (Intent intent,int Startid) is invoked after the OnCreate () method call {
        Toast.maketext (This, "Musicservice OnStart", Toast.length_short). Show ();
        LOG.I (Tag, "Musicservice OnStart ()");
    Mplayer.start (); This method is called when the service is destroyed @Override public void OnDestroy () {Toast.maketext (this, Musicservice OnDestroy ()),
        Toast.length_short). Show ();
        Mplayer.stop ();
    LOG.I (Tag, "Musicservice OnDestroy ()"); }
}

4, code in Mainhelloservice.java:

Package android.basic.lesson14;
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 Mainhelloservice extends activity {//label String tag = "Musicservice" for the log tool; /** 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 (Mainhelloservice.this, "Mainhelloservice onCreate", Toast.length_short). Show ();

    LOG.I (Tag, "Mainhelloservice onCreate");
    Defines the Component Object button b1= (button) Findviewbyid (R.ID.BUTTON01);
    Button b2= (button) Findviewbyid (R.ID.BUTTON02); BUtton b3= (Button) Findviewbyid (R.ID.BUTTON03);

     Button b4= (button) Findviewbyid (r.id.button04); Define service link Object final serviceconnection conn = new Serviceconnection () {@Override public void OnS erviceconnected (componentname name, IBinder service) {Toast.maketext (Mainhelloservice.this, "Serviceconne
                Ction onserviceconnected ", Toast.length_short). Show ();

            LOG.I (Tag, "Serviceconnection onserviceconnected"); @Override public void onservicedisconnected (componentname name) {Toast.maketex
                T (mainhelloservice.this, "Serviceconnection onservicedisconnected", Toast.length_short). Show ();

            LOG.I (Tag, "Serviceconnection onservicedisconnected");

        }}; 
                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 (Mainhelloservice.this,android.basic.lesson14.musicservice.class); Switch (V.getid ()) {case R.ID.BUTTON01://Start Service StartService (Intent)
                    ;
                Break
                    Case R.ID.BUTTON02://Stop Service StopService (intent);
                Break
                    Case R.ID.BUTTON03://Binding service Bindservice (intent,conn,context.bind_auto_create);
                Break
                    Case R.ID.BUTTON04://Unbound unbindservice (conn);
                Break

    }
            }
    };
    Binding fixed-point hit Listener b1.setonclicklistener (OCL);
    B2.setonclicklistener (OCL);
    B3.setonclicklistener (OCL);  

  B4.setonclicklistener (OCL);
        @Override public void OnDestroy () {Super.ondestroy (); Toast.maketext (Mainhelloservice.this, "Mainhelloservice OnDestroy", Toast.
        Length_short). Show ();
  LOG.I (Tag, "Mainhelloservice OnDestroy"); }
}

Above is the introduction of the Android service, follow-up to continue to supplement the relevant information, thank you for your support for this site!

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.