One of the four major components of Android-Service (1)

Source: Internet
Author: User
Tags call back hosting

Android has four components: Activity, broadcast explorer, service, and content providers;

Today, I will introduce the service first. The service function is similar to the activity (this will be described in detail in subsequent articles). The service can be said to be an activity without a trial view, that is, a hidden activity.

Below is the official website:

A service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. each service class must have a corresponding
<Service> Declaration in its package's androidmanifest. xml. Services can be started with context. startservice () and context. bindservice ().

Note that services, like other application objects, a service runs in the main thread of its hosting process-the service doesNotCreate
Its own thread and doesNotRun in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such
As MP3 playback or networking) operations, you shoshould create a new thread within the service to do that work. By using a separate thread,
You will reduce the risk of application not responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

(Probably: as a service, it indicates that an application requires a long operation and the user does not interact, or is used by another application. Each service must be registered in androidmanifest. xml. Service passedContext. startservice ()AndContext. bindservice ()Start.

Notes:

The service is in the main thread.Hosting ProcessRun, not creating your own thread and not in another process (unless you specify one ). This means that,If the service interacts frequently with the CPU (high-load CPU operations) or is blocked, you need to create a new thread to do the work.. Intentservice inherits from the service and has its own thread to handle the desired thing in the thread .)

)

 

Two Service Modes(Startservice ()/bindservice () is not completely isolated) (1) Local ServiceLocal Service is used Internal Application.

It can be started and run, Until someone stops it or stops it.. In this way, it starts by calling context. startservice () and ends by calling context. stopservice. It can call service. stopself () or service. stopselfresult () to stop itself.. No matter how many times the startservice () method is called, you only need to call stopservice () once to stop the service. It is used to implement some time-consuming tasks of the application itself, such as querying the upgrade information. It does not occupy the application, such as the thread to which the activity belongs, but is executed in the single-thread background, so that the user experience is better. (2) Remote ServiceRemote service is used in the Android system Between applications.

It can perform program operations through APIS defined and exposed by itself.. The client establishes a connection to the service object and calls the service through that connection. Connection to call the context. bindservice () method to establish, to call context. unbindservice () to close. Multiple clients can be bound to the same service.. If the service is not loaded yet, bindservice () loads it first.
It can be reused by other applications, such as the weather forecast service. Other applications do not need to write such services any more. You can call the existing services..

 

The following describes the service content:

Service lifecycle;

Lcoal service;

Remote service;

First introduce the lifecycle (lifecircile)

The system has two methods to start the service. If you call context. startservice (), the system will get this service (if necessary, create it and call its oncreate () method), and then call its onstartcommand (intent, INT) method. The service starts to run until the context. stopservice () or stopself () method is called. Note that context is called multiple times. startservice () is not nested (that is, oncreate will only be called once (the service will only be created once, if it has already been created, it will not be created), then the corresponding onstart () method will be called ), therefore, no matter how many times a service is started, once the context is called. stopservice () or stopself.

The client can also use context. bindservice () to obtain a permanent link to the service. This method also creates a service (oncreate () without running the service, but does not call onstart (). The client will obtain the ibinder object returned by the onbind (intent) method of the service, which is used to allow the client to call back the service method. As long as the connection has been established, the Service will continue to run (whether or not the client retains the reference of the Service's ibinder object ). Generally, the returned ibinder object is a complex interface defined in aidl.

The service can also be bound when started or started when bound;

Summary:

1. Start through startservice, oncreate-> onstartcommand-> onstart (if the service has already been created, oncreate will not be called );

2. Stop the service by calling ondestroy-> stopservice ;(The caller directly exits without calling stopservice.,Then the service will always run in the background)

3. Start through bindservice and only call oncreate. servicedemo and service will be bound at this time;

4. Call onunbind-> ondestroy by calling. If it is bound to activity, it will coexist with activity;

5. Hybrid startup:

/**
* 1. No matter whether a service is bound or created, the service will only be created once (that is, oncreate will only be called once)
* 2. If you have already started, bind
* 3. If bind already exists, start
* 4. If you have already started and bind, you cannot use stopservice. You can only use unbind and then call onstop (this will not be called)
* 5. If BIND is already in use and start is enabled, stopservice does not work. You can only use unbind and then call onstop (this will not be called)
*/

6. Start the service. There are two additional modes based on the onstartcommand return value:

A. start_sticky is used to display start and stop services. B. start_not_sticky or start_redeliver_intent is used in the mode where a command needs to be processed.

 

Processes with services have a high priority.The official documentation tells us that the Android system will try to keep the process with service running as long as the service has been started (start) or the client connection (bindservice) to it. When the memory is insufficient, it must be maintained. Processes with services have a high priority.
1. if the service is calling the oncreate, onstartcommand, or ondestory method, the process used for the current service changes to the foreground process to avoid being killed.


2. if the current service has been started, processes with it have lower priority than processes visible to users, but are more important than invisible processes, this means that the service is generally not killed.


3. If the client has been connected to the Service (bindservice), the process with the service has the highest priority and can be considered as visible.


4. If the service can use the startforeground (INT, notification) method to set the service to the foreground state, the system considers the service to be visible to the user and will not killed the service when the memory is insufficient.

If other application components run in the same process as services and activities, the importance of the process will be increased.

 

 

This is the local service startup and binding

Code:

Potatoservice. Java

Package COM. potato; import Java. io. filedescriptor; import Java. io. printwriter; import android. app. notification; import android. app. icationicationmanager; import android. app. pendingintent; import android. app. service; import android. content. context; import android. content. intent; import android. content. res. configuration; import android. OS. binder; import android. OS. ibinder; import android. util. log; public class potatoservice extends Service {private final static string tag = "potatoservice"; private icationicationmanager micationicationmanger; // This is the object that contains es interactions from clients. see // remoteservice for a more complete example. private Final ibinder mbinder = new localbinder (); @ overridepublic ibinder onbind (intent arg0) {// todo auto-generated method stublog. D (TAG, "onbind"); Return mbinder ;}@ overrideprotected void dump (filedescriptor FD, printwriter writer, string [] ARGs) {// todo auto-generated method stubsuper. dump (FD, writer, argS) ;}@ overrideprotected void finalize () throws throwable {// todo auto-generated method stubsuper. finalize () ;}@ overridepublic void onconfigurationchanged (configuration newconfig) {// todo auto-generated method stubsuper. onconfigurationchanged (newconfig) ;}@ overridepublic void oncreate () {// todo auto-generated method stubsuper. oncreate (); log. D (TAG, "oncreate"); mnotificationmanger = (icationicationmanager) getsystemservice (context. notification_service); shownotification () ;}@ overridepublic void ondestroy () {// todo auto-generated method stubsuper. ondestroy (); log. D (TAG, "ondestroy"); mnotificationmanger. cancel (icationication_id) ;}@ overridepublic void onlowmemory () {// todo auto-generated method stubsuper. onlowmemory (); log. D (TAG, "onlowmemory") ;}@ overridepublic void onrebind (intent) {// todo auto-generated method stubsuper. onrebind (intent); log. D (TAG, "onrebind") ;}@ overridepublic void onstart (intent, int startid) {// todo auto-generated method stubsuper. onstart (intent, startid); log. D (TAG, "onstart") ;}@ overridepublic int onstartcommand (intent, int flags, int startid) {// todo auto-generated method stublog. D (TAG, "onstartcommand"); string data = ""; Data = intent. getextras (). getstring ("pass_data_to_service"); log. D (TAG, data); return Super. onstartcommand (intent, flags, startid) ;}@ overridepublic Boolean onunbind (intent) {// todo auto-generated method stublog. D (TAG, "onunbind"); return Super. onunbind (intent);} // call (servicedemo) to get the service and operate it on public class localbinder extends binder {potatoservice getservice () {return potatoservice. this ;}} int notification_id = 119527; Public void shownotification () {Notification = new notification (R. drawable. ic_launcher, "potatoservice started", system. currenttimemillis (); pendingintent = pendingintent. getactivity (this, 0, new intent (this, servicedemoactivity. class), 0); notification. setlatesteventinfo (this, "potato service", "service start", pendingintent); micationicationmanger. Y (ication_id _id, notification );}}

Servicedemoactivity. Java

Package COM. potato; 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. view. view; import android. widget. button;/***** @ author Justin * 1. service is actually an activity that is not displayed (activity that cannot be seen) ** 2. if you compare the charges in oncreate and onstart of the service It is best to start a new thread to run the Service * (because the service is run in the main thread, otherwise the UI operation or other things in the main thread are blocked) **/public class servicedemoactivity extends activity {/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); Init () ;}potatoservice mpotatoservice; Boolean misautobind = false;/*** binds activity and service to survive together */Private serviceconnection mserviceconnection = new serviceconnection () {@ overridepublic void onserviceconnected (componentname, ibinder Service) {// todo auto-generated method stubmpotatoservice = (potatoservice. localbinder) Service ). getservice () ;}@ overridepublic void onservicedisconnected (componentname name) {// todo auto-generated method stubmpotatoservice = NULL ;}; void Init () {butto N btnstartservice = (button) findviewbyid (R. id. btn_start_service); btnstartservice. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view arg0) {// todo auto-generated method stubstartservice () ;}}); button btnstopservice = (button) findviewbyid (R. id. btn_stop_service); btnstopservice. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view arg0) {// Do auto-generated method stubstopservice () ;}}); button btnbindservice = (button) findviewbyid (R. id. btn_bind_service); btnbindservice. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view arg0) {// todo auto-generated method stubbindservice () ;}}); button btnunbindservice = (button) findviewbyid (R. id. btn_unbind_service); btnunbindservice. setonclicklistener (new view. onclickl Istener () {@ overridepublic void onclick (view arg0) {// todo auto-generated method stubunbindservice ();}});} /*** oncreate-> onstartcommand-> onstart */private void startservice () {intent = new intent (this, potatoservice. class); intent. putextra ("pass_data_to_service", "do you receive? "); Startservice (intent);}/*** the caller directly exits without calling stopservice, so the service will always run in the background, ondestroy */private void stopservice () {intent = new intent (this, potatoservice. class); stopservice (intent);}/*** only oncreate is called. At this time, servicedemo and Service */private void bindservice () {intent = new intent (this, potatoservice. class); bindservice (intent, mserviceconnection, context. bind_auto_create); misautobind = true;}/*** if servicedemo exits, the service will call onunbind-> ondestroy to survive */private void unbindservice () {If (misautobind) {unbindservice (mserviceconnection); misautobind = false ;}}/*** 1. no matter whether you bind or create a service, the service will only be created once (that is, oncreate will only be called once) * 2. if you have already started, bind * 3. if bind already exists, start * 4. if you have already started and bind, you cannot use stopservice. You can only use unbind, and then call onstop (this will not be called) * 5. if BIND is already in use and start is enabled, stopservice does not work. You can only use unbind, and then call onstop (this will not be called )*/}

Add the code in androidmainfest. XML to register the service)

<service android:enabled="true" android:name=".PotatoService"></service>

Main. xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" ><Button    android:id="@+id/btn_start_service"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="start_service" /><Button    android:id="@+id/btn_stop_service"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="stop_service" /><Button    android:id="@+id/btn_bind_service"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="bind_service" /><Button    android:id="@+id/btn_unbind_service"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="unbind_service" /></LinearLayout>

Finally, we provide an auxiliary image of lifeservice provided by the Shangguan website to help you understand:

By implementing these methods, You can monitor two nested loops of the Service's lifecycle:
The entire lifetime of a serviceHappens between the time oncreate () is called and the time ondestroy () returns. like an activity, a service does its initial setup in oncreate () and releases all remaining resources in ondestroy (). for example,
A music playback service cocould create the thread where the music will be played in oncreate (), then stop the thread in ondestroy ().

The oncreate () and ondestroy () methods are called for all services, whether they're created by startservice () or bindservice ().

The active lifetime of a serviceBegins with a call to either onstartcommand () or onbind (). Each method is handed the intent that was passed to either startservice () or bindservice (), respectively.

If the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even after onstartcommand () returns ). if the service is bound, the active lifetime ends when onunbind () returns. if the service is started,
The active lifetime ends the same time that the entire lifetime ends (the service is still active even after onstartcommand () returns ). if the service is bound, the active lifetime ends when onunbind () returns.

Note: although a started service is stopped by a call to either stopself () or stopservice (), there is not a respective callback for the Service (There's no onstop () callback ). so, unless the service is bound to a client, the system destroys it when the service
Is stopped-ondestroy () is the only callback parameter ed.

Figure 2 into strates the typical callback methods for a service. although the figure separates services that are created by startservice () from those created by bindservice (), keep in mind that any service, no matter how it's started, can potentially allow
Clients to bind to it. so, a service that was initially started with onstartcommand () (by a client calling startservice () can still receive a call to onbind () (when a client CILS bindservice ()).

2012/5/30 modify

Note:
1. The service is in the main thread.Hosting ProcessRun,No thread created and not in another process(Unless you specify one ).

2. This means that,If the service interacts frequently with the CPU (high-load CPU operations) or is blocked,

3. You need to create a new thread to do the work.. Intentservice inherits from the service and has its own thread to process what you want.

Leave a message if you have any questions.

Or mail ligexiao@gmial.com

Source code:

Http://download.csdn.net/detail/alex0203/3834762

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.