Android notes. Getting started with Service components (1). What is Service ?, Android. service

Source: Internet
Author: User

Android notes. Getting started with Service components (1). What is Service ?, Android. service

Reprinted please indicate Source: http://blog.csdn.net/u012637501 (embedded _ small J of the sky)
I. Service1. Service IntroductionThe Service is one of the four Android components. Similar to the Activity component, the Service represents executable programs and has its own life cycle, the only difference is that the Activity component provides an interface to facilitate human-computer interaction, while the Service only runs in the background without an interactive interface. A Service is a component in the android system. It is derived from Context, but it cannot run on its own. It can only run in the background and interact with other components. It needs to be called through an Activity or other Context object. It should be noted that the Service is not a separate process or a separate thread to Prevent the application from being unresponsive errors. It runs in the main thread of its hosted process like other application objects. Of course, if we want our Service to run MP3 or network downloads in the background, we can create a thread for implementation.2. Service LifecycleBecause the Service can be started in two ways: Context. startService () and Context. bindService (). (1) Context. startService () method: This method is used to start the Service. There is no association between the visitor (client) and the Service. Even if the visitor exits, the Service still runs. Call Context. startService ()-> onStartCommand (Intent, int, int)-> Service Running-> Context. stopService () or stopSelf ()-> onDestory ()-> Service is disabled (2) Context. bindService () method: This method is used to start the Service. The visitor (client) is bound with the Service. Once the visitor exits, the Service is terminated. Call Context. method of Service lifecycle triggered by startService (): onCreate ()-> OnBind (Intent)-> bind the client to Service-> OnUnbind ()-> onDestory ()-> Service is Disabled

Sublimation note. when the Context. when the bindService () method starts a Service, the onStartCommand (Intent, int, int) method is not executed; 2. when Activity (client Activiy) calls BindService () to bind a started Service (the Activity is initially started using the startService () method, the system only transmits the IBinder object inside the Service (returned by the onBind () method) to the acitinder, and does not completely "bind" the Service lifecycle to the Activity, therefore, when the Activity calls the unBindService () method to cancel binding to the Service, it only disconnects the Activity from the Service and cannot stop the Service component. 3. API-ServicePublic abstract class Service (1) Inheritance relation java. lang. object upload android. content. context encryption android. content. contextWrapper extends android. app. service (2) constructor Service (). However, when developing a Service, we mainly use Content. getService () method to obtain Service class objects. (3) common methods (Service component method)> void OnCreate (): this Service will be called immediately after it is created for the first time;> public int onStartCommand (Intent intent, int flags, int startId): This method is called back every time the client calls the startService (Intent intent) method to start the Service.> public abstract boolean stopService (Intent service ): the client calls this method to disable Service> public final void stopSelf (): Service automatic close> public abstract IBinder onBind (Intent intent): This method is a required method for Service subclass, it returns an IBinder object through which client applications can interact with Service components. Communication. The Intent object is used to bind the client to the Service and pass it to Context. bindService.> Boolean onUnbind (Intent intent): This method is called when all clients bound to this Service are disconnected> void onDestory (): this method will be called before the Service is closed, and the Service will clean up all resources it occupies (including all threads and recipients registered on the Service ). 4. Service Startup Mode(1) Context. startService () starts when the client (Component) starts the Service through startService () of Context, the visitor and Service are not associated, and the Service will be executed in the background all the time, even if the process that calls startService is finished, the Service still exists until a process calls stopService () or the Service commits suicide (stopSelf ()). in this case, the Service and the visitor cannot communicate or exchange data. (2) After Context. bindService () is started to bind a Service through bindService () of Context, Servcice and the component that calls bindService () are both dead. That is to say, when the component that calls bindService () is destroyed, the Service it binds will also be terminated. Ii. Basic Idea of Service Development (local) 1. Create and configure a Service(1) define a subclass that inherits from the Service. If you want the Service component to do something, you only need to define the relevant business code in the onCreate () or onStartCommand () method. The framework of a Service component is as follows: \ src \ service \ FirstService. java
public class FirstService extends Service
{
    / * a. A method that must be implemented to return an IBinder object to the client for communication
     * Since we call the startService method to start a Servie, there is no need to bind to the client (component), so the return is null.
     * /
    @Override
    public IBinder onBind (Intent arg0)
    {
            return null;
    }
    /*b.Service is called when the service is created * /
    @Override
    public void onCreate ()
    {
            super.onCreate ();
            System.out.println ("Service is Created");
    }
    /*c.Call this method when Service is started * /
    @Override
    public int onStartCommand (Intent intent, int flags, int startId)
    {
        Sytem.out.println ("Service is Started");
        return START_STICKY;
    }
    /*d.Service callback before being closed * /
    @Override
    public void onDestroy ()
    {
          super.onDestroy ();
            System.out.println ("Service is Destroyed");
    }
}


2. Configure the Service in the AndroidManifest.xml file After defining the above Service, you need to configure the Service in the AndroidManifest.xml file. Configure the Service to use the <service ../> element. Similar to configuring Activity, when you configure Service, you can also configure <intent-filter ../> sub-elements for <service ../> elements, which are used to indicate which Intents this Service can start.
<!-Configure a Service component->
<service
        android: name = ". FirstService">
        <intent-filter>
                <!-Configure action for the intent-filter of the service component->
                  <action android: name = "com.example.service.FIRST_SERVICE" />
         </ intent-filter>
</ service>
    The value in Action must be consistent with the value of the Intent Action created in the program, the program is to find the corresponding Service according to the value of Action to start it. Service is the most similar component to Activity among the four major components of Android, and they all represent executable programs. Therefore, developing a Service is similar to developing an Activity. We only need to define a subclass that inherits Service and configure the Service in the AndroidManifest.xml file to run the Serviec in the program. How to start a Service? We can start a service through the Context.startService () method or Context.bindService () method in the Activity subclass of this application, or through the Context.startService () method or Context.bindService in the Activity subclass of another application () Method to start this service.
3. Start and stop the service When the development of the service is completed, we can start the service in the Activity subclass of our application, or we can start the service in other applications. Here, we start (close) the Service in this application, using the Content.startService (Intent intent) method. \ src \ service \ StartService
public class StartServiceTest extends Activity
{
    Button start, stop;
    @Override
    public void onCreate (Bundle savedInstanceState)
    {
            super.onCreate (savedInstanceState);
            setContentView (R.layout.main);
            // Get the start and stop buttons in the program interface buttons
            start = (Button) findViewById (R.id.start);
            stop = (Button) findViewById (R.id.stop);
            // Create an Intent to start the Service
            final Intent intent = new Intent ();
            // Set the Action property for Intent
             intent.setAction ("com.example.service.FIRST_SERVICE");
             start.setOnClickListener (new OnClickListener () {
                        @Override
                        public void onClick (View arg0)
                        {
                                // Start the specified Service
                                startService (intent);
                        }
                });
                stop.setOnClickListener (new OnClickListener () {
                        @Override
                        public void onClick (View arg0)
                        {
                                // Close the specified Service
                                stopService (intent);
                        }
                });
    }
}
     Through the above 3 steps, we have completed a Service and an application using the Service (Service is an integral part of the application).
Sublimation Note 3: 1. Set the Action attribute for Intent, the main role is to specify which Service to start. Among them, "com.example.service.FIRST_SERVICE" configures the action attribute of the Service in the <intent-filter ../> sub-element of the <service ../> element in the AndroidManifest.xml configuration file of the Service. 2. The Activity starts the specified Service through the Content.startService (Intent intent) method, the onCreate method will be called back every time the Service is created, the onStart method will be called back every time the Service is started-multiple times to start an existing Service component The onCreate method will no longer be called, but the onStartCommand () method will be called every time it is started.

Reference: http://wear.techbrood.com/reference/android/app/Service.html 

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.