The lifecycle and use of service for four Android components

Source: Internet
Author: User

Service Introduction:Service is one of the four components of Android, usually for a long-term background task without a UI interface, even when the program exits, the background task is still executing. For example: Music playback.
Service error:1.service executes in the UI thread. 2. It is not possible to perform time-consuming tasks in the service because the service is running in the UI thread. 3. If you need to perform a time-consuming task in the background, you must open a thread in the service to execute it.
Service life cycle:

two ways to start and stop a service1.context.startservice (); Context.stopservice ().2.context.bindservice (); Context.unbindservice ().


Service Usage Example 1:The client code is as follows:
Package Com.xjp.broadcast;import Android.app.activity;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.TextView;public    Class Mainactivity extends Activity {Private final static String action = "com.xjp.MainActivity";    Private TextView result;    Private Button StartService;    Private Button StopService; Private Broadcastreceiver Broadcastreceiver = new Broadcastreceiver () {@Override public void onreceive (Cont            Ext context, Intent Intent) {int i = Intent.getintextra ("key", 0);        Result.settext (i + "");    }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        result = (TextView) Findviewbyid (R.id.result); StartService = (Button)Findviewbyid (R.id.startservice);                 Startservice.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Intent service = new Intent (mainactivity.this, Calculationservice.class);            StartService (service);        }        });        StopService = (Button) Findviewbyid (R.id.stopservice);                Stopservice.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Intent service = new Intent (mainactivity.this, Calculationservice.class);            StopService (service);    }        });        } @Override protected void Onresume () {super.onresume ();    Initfilter ();        } @Override protected void OnDestroy () {Super.ondestroy ();    Unregisterreceiver (Broadcastreceiver);        } private void Initfilter () {intentfilter filter = new Intentfilter ();        Filter.addaction (action); RegIsterreceiver (broadcastreceiver, filter); }}

1. Click "Start Service" and "stop Service", then the life cycle print result is as follows:


2. Click "Start Service" two times to print the results as follows:


this way you can start the same service multiple times, and only execute onCreate the first time. After the second time, only the Onstartcommand is executed, and the service still runs in the background when and only after the app exits. After exiting, look at the running app in the settings:



The service-side code is as follows:
Package Com.xjp.broadcast;import Android.app.service;import Android.content.intent;import android.os.IBinder; Import android.util.log;/** * Description: * USER:XJP * DATE:2015/5/4 * time:14:14 */public class Calculationservice ex    Tends Service {Private final static String TAG = "Calculationservice";    Private final static String action = "com.xjp.MainActivity";    Private Boolean quit = false;        @Override public IBinder onbind (Intent Intent) {log.e (TAG, "====onbind=====");    return null;        } @Override public boolean onunbind (Intent Intent) {log.e (TAG, "====onunbind=====");    return Super.onunbind (Intent);        } @Override public void OnCreate () {LOG.E (TAG, "====oncreate=====");    Super.oncreate (); } @Override public int onstartcommand (Intent Intent, int flags, int startid) {log.e (TAG, "====onstartcommand        =====");        Startthread ();    Return Super.onstartcommand (Intent, flags, Startid); } @Override    public void OnDestroy () {LOG.E (TAG, "====ondestroy=====");        Quit = true;    Super.ondestroy ();            }/** * Open thread emulation time-consuming task */public void Startthread () {new Runnable () {int i = 0;                    @Override public void Run () {while (I < &&!quit) {                        try {thread.sleep (1000);                        i++;                        Intent Intent = new Intent (action);                        Intent.putextra ("Key", I);                    Sendbroadcast (Intent);                    } catch (Interruptedexception e) {e.printstacktrace ();    }}}). Start (); }}



Service Usage Example 2:The client code is as follows:
Package Com.xjp.broadcast;import Android.app.activity;import Android.content.broadcastreceiver;import Android.content.componentname;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.content.serviceconnection;import Android.os.Bundle;import Android.os.ibinder;import Android.view.view;import Android.widget.button;import Android.widget.TextView;public    Class Mainactivity extends Activity {Private final static String action = "com.xjp.MainActivity";    Private TextView result;    Private Button StartService;    Private Button StopService;    Private Calculationservice Calculationservice; Private Broadcastreceiver Broadcastreceiver = new Broadcastreceiver () {@Override public void onreceive (Cont            Ext context, Intent Intent) {int i = Intent.getintextra ("key", 0);        Result.settext (i + "");    }    }; Private Serviceconnection serviceconnection = new Serviceconnection () {@Override public void onserviceconnected (componentname name, IBinder service) {Calculationservice = ((Calculati            Onservice.calulationbinder) service). GetService ();        Calculationservice.startthread ();        } @Override public void onservicedisconnected (componentname name) {calculationservice = null;    }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        result = (TextView) Findviewbyid (R.id.result);        StartService = (Button) Findviewbyid (R.id.startservice);                 Startservice.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Intent service = new Intent (mainactivity.this, Calculationservice.class);            Bindservice (service, serviceconnection, context.bind_auto_create);        }        }); StopService = (Button) findviewByid (R.id.stopservice);                Stopservice.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Unbindservice (serviceconnection);    }        });        } @Override protected void Onresume () {super.onresume ();    Initfilter ();        } @Override protected void OnDestroy () {Super.ondestroy ();    Unregisterreceiver (Broadcastreceiver);        } private void Initfilter () {intentfilter filter = new Intentfilter ();        Filter.addaction (action);    Registerreceiver (broadcastreceiver, filter); }}

The service-side code is as follows:
<pre name= "code" class= "java" >package com.xjp.broadcast;import Android.app.service;import Android.content.intent;import android.os.binder;import android.os.ibinder;import android.util.Log;/** * Description : * USER:XJP * DATE:2015/5/4 * time:14:14 */public class Calculationservice extends Service {private final static S    Tring TAG = "Calculationservice";    Private final static String action = "com.xjp.MainActivity";    Private Boolean quit = false;    Private IBinder binder = new Calulationbinder (); public class Calulationbinder extends Binder {public Calculationservice getService () {return Calculati        Onservice.this;        }} @Override public IBinder onbind (Intent Intent) {log.e (TAG, "====onbind=====");    return binder;        } @Override public boolean onunbind (Intent Intent) {log.e (TAG, "====onunbind=====");    return Super.onunbind (Intent); } @Override public void OnCreate () {LOG.E (TAG, "====oncreate===== ");    Super.oncreate (); } @Override public int onstartcommand (Intent Intent, int flags, int startid) {log.e (TAG, "====onstartcommand        =====");        Startthread ();    Return Super.onstartcommand (Intent, flags, Startid);        } @Override public void OnDestroy () {LOG.E (TAG, "====ondestroy=====");        Quit = true;    Super.ondestroy ();            }/** * Open thread emulation time-consuming task */public void Startthread () {new Runnable () {int i = 0;                    @Override public void Run () {while (I < &&!quit) {                        try {thread.sleep (1000);                        i++;                        Intent Intent = new Intent (action);                        Intent.putextra ("Key", I);                    Sendbroadcast (Intent);                    } catch (Interruptedexception e) {e.printstacktrace ();               } }}). Start (); }}


Click the "Start Service" button and the "Stop Service" button once, the life cycle printing results are as follows:


The binding service, if the exit is not unbound, that is, no callcontext.Unbindservice (). Then, the error will be reported. Therefore, the context is generally called in the client's Ondestory () .  Unbindservice (). So this service is not suitable for long-time tasks in the background. This service binding and unbinding are paired.

Two types of service summary:
The first, non-binding service, when the app exits, can not stop services from exiting. You can keep the service running in the background. Disadvantage: Starting the service is to start the background task, not very good in the client at any time to control the service's background task execution times. Second, the bound service, the application exits must unbind the service, or the program error. Advantage: However, the bundled service can obtain the service binder, and can flexibly control the invocation of various methods in the service.

The lifecycle and use of service for four Android components

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.