Detailed explanation and use of the service in Android

Source: Internet
Author: User

Detailed explanation and use of the service in Android:

  1. Concept:
    (1). A service can be said to be an activity that runs in the background. It's not a separate process, it just needs to be used by the app to tell it what to do in the background.
    (2). If it implements the interaction with the user, it needs to receive the display via the notification bar or by sending the broadcast, the UI.
    (3). It is widely used, especially in the framework layer, where the application is more of a call to system services.
  2. Role:
    (1). It is used to handle some background operations that do not interfere with the user's use. Download below, network access. Play the music, he can be opened by intent, but also can be bound to the host object (caller such as activity) to use.
    (2). If activity is the information that displays the foreground page, then the service is operated in the background. If the service interacts with the foreground UI, you can send a broadcast or notification bar.
  3. Life cycle:
    (1). The lifetime of the service is started from OnCreate () and is called Until the OnDestroy () method returns. Like activity, the service initializes its work in OnCreate (), releasing the remaining resources in OnDestroy ().
    (2). **startservice () Way: **oncreate ()->onstartcommand ()->onstart ()->ondestroy ()
    (3). **bindservice () Way: **oncreate ()->onbinder ()->onunbind ()->ondestroy (). When the Onunbind () method returns, it ends.

  4. Starting mode:
    (1). The service cannot run itself and needs to be invoked through an activity or other context object.
    (2). There are two ways to start a service:
    Context.startservice () and Context.bindservice () Start the service in two ways. If there is a time-consuming operation in the OnCreate () method of the service or in the OnStart () method, a new thread is opened. Start in both ways where service is required.
    Note:
    The usual use of many is the StartService method, you can put some time-consuming tasks in the background to deal with, when the processing is completed, can be broadcast or notification bar to notify the front desk.

  5. Here's an in-depth understanding of the code:

    (1). Mainactivity.java class:

 PackageCom.example.servicetest;ImportCom.example.servicetest.service.MyService;Importandroid.app.Activity;ImportAndroid.content.ComponentName;ImportAndroid.content.Intent;ImportAndroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public  class mainactivity extends Activity implements Onclicklistener  {    /** Flag bit * /    Private StaticString TAG ="Com.example.servicetest.MainActivity";/** Start Service * /    PrivateButton Mbtnstart;/** Binding Service * /    PrivateButton Mbtnbind;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); }/** * Init the View * *    Private void Initview() {Mbtnstart = (Button) Findviewbyid (R.id.startservice);        Mbtnbind = (Button) Findviewbyid (R.id.bindservice); Mbtnstart.setonclicklistener ( This); Mbtnbind.setonclicklistener ( This); }@Override     Public void OnClick(View view) {Switch(View.getid ()) {//How to start the service         CaseR.id.startservice:startservice (NewIntent (myservice.action)); Break;//How the service is bound         CaseR.id.bindservice:bindservice (NewIntent (myservice.action), Conn, bind_auto_create); Break;default: Break; }} Serviceconnection conn =NewServiceconnection () { Public void onserviceconnected(componentname name, IBinder service) {LOG.V (TAG,"onserviceconnected"); } Public void onservicedisconnected(componentname name) {LOG.V (TAG,"onservicedisconnected"); }    };@Override    protected void OnDestroy() {Super. OnDestroy (); System.out.println ("-------OnDestroy ()--"); StopService (NewIntent (myservice.action));    Unbindservice (conn); }}

(2). Myservice.java class:

 PackageCom.example.servicetest.service;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;ImportAndroid.util.Log; Public  class myservice extends Service {    /** Flag bit * /    Private StaticString TAG ="Com.example.servicetest.service.MyService";/** behavior * /     Public Static FinalString ACTION ="Com.example.servicetest.service.MyService";@Override     Public void onCreate() {Super. OnCreate (); System.out.println ("-----onCreate ()---"); }@Override     Public void OnStart(Intent Intent,intStartid) {Super. OnStart (Intent, Startid); System.out.println ("-----onStart ()---"); }@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {System.out.println ("-----onstartcommand ()---");return Super. Onstartcommand (Intent, flags, Startid); }@Override     PublicIBinderOnbind(Intent arg0) {System.out.println ("-----onbind ()---");return NULL; }@Override     Public void Onrebind(Intent Intent) {System.out.println ("-----onrebind ()---");Super. Onrebind (Intent); }@Override     Public Boolean Onunbind(Intent Intent) {System.out.println ("-----onunbind ()---");return Super. Onunbind (Intent); }@Override     Public void OnDestroy() {System.out.println ("-----OnDestroy ()---");Super. OnDestroy (); }}

(3). Androidmanifest.xml

<!--registration --        <service android:name="Com.example.servicetest.service.MyService" >            <intent-filter>                <!--Intent to start the service                <action android:name="Com.example.servicetest.service.MyService" />                 <category android:name="Android.intent.category.default" />            </intent-filter>        </Service>


StartService Method:
(1). When pressing the StartService button: the following:

(2). Then continue pressing the StartService button: the following:

Bindservice Method:
(1). When pressing the Bindservice button: the following:

(2). Then continue pressing the Bindservice button: the following:

(3). Press the StartService button and press the Bindservice button: the following:

Detailed explanation and use of the service in Android

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.