Android Service Review

Source: Internet
Author: User

A service is a combination of applications and runs in the background. It can perform a long operation, but does not provide a user interface.

The application is terminated, and the service is not terminated either .... Each service must be declared in manifest through <service>. You can start it through contect. startservice and contect. bindserverice ..
Like other application components, the service runs in the main process. This means that if the service requires a lot of time-consuming or congested operations, it needs to be implemented in its subthread.
The two service modes (startservice ()/bindservice () are not completely separated ):
The local service is used inside the application.

It can be started and run until someone stops it or it 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 server. 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.
Remote service is used between applications in the Android system.
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 and can call existing services.
Main differences between the two service methods for starting a service
1. startservice.
The startservice () method is used to enable the service. There is no relation between the caller and the service. Even if the caller exits, the Service continues to run.
If you plan to use context. the startservice () method starts the service. when the service is not created, the system first calls the oncreate () method of the service and then calls the onstart () method (onstartcommond () has been changed after 2.0 () method ).
If the service has been created before the startservice () method is called, multiple call of the startservice () method will not lead to multiple creation of the service, but will lead to multiple calls of the onstart () method.
A service started using the startservice () method can only end the service by calling the context. stopservice () method. The ondestroy () method is called when the service ends. Or stop it by yourself.
2. bindservice ()-enabled; (asynchronous)
The caller and the service are bound together. Once the caller exits, the service is terminated. This feature has the following features: "The caller does not want to live at the same time and must die at the same time.
Onbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller binds to the service. When the caller and the service are already bound, multiple calls to the context. bindservice () method will not cause this method to be called multiple times.
When the context. bindservice () method is used to start a service, only the onunbind () method can be called to release the caller and the service. When the service ends, the ondestroy () method is called.

Service lifecycle: (not described)


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.
Analyze the functions of the onstartcommand method parameters and return values:
1. Depending on the return value of this method, there can be two startup modes: start_not_sticky and start_sticky (whether to restart when the method is killed. If the parameter is start_redeliver_intent, it indicates that when the process in which the service is located is killed, the service is restarted and intent content is re-transmitted. The other two parameters do not re-pass intent, and both are null)
2. If start_redeliver_intent is returned, no matter how many times it is started, the number of times it will be restarted.
3. Mark the current service
4. The third parameter startid indicates the number of times the Service is currently started.

Let's take a look at the test source code:

Helloserivce. Java

Public class helloservice extends Service {handler = new handler (); private final ibinder mbinder = new hellobinder (); @ overridepublic void oncreate () {log. V ("verbose", "oncreate"); super. oncreate ();}/*** in this way, after the service is started from the activity, it runs in the background and is not associated with the activity. If there is a bind method *, communication with the activity throughout the process ** Based on the return value of this method, there can be two startup modes: start_not_sticky, start_sticky, * start_redeliver_intent, whether to automatically restart after the service is killed by the system, and whether to re-pass intent. * If the service is restarted after it is killed, the oncreate and onstartcommand Methods * will be re-called. However, when onstartcommand is re-called, the parameter will not be passed again .. * If start_redeliver_intent is returned, no matter how many times it is started, the number of times it will be restarted. * // @ Overridepublic int onstartcommand (intent, int flags, int startid) {log. V ("verbose", "onstartcomand"); handler. post (New runnable () {// submit it to @ overridepublic void run () {toast through a common handler thread and UI thread. maketext (getapplicationcontext (), "Start service", toast. length_long ). show () ;}}); // return Super. onstartcommand (intent, flags, startid); Return start_redeliver_intent;} @ overridepublic void ondestroy () {log. V ("verb Ose "," ondestory "); handler. post (New runnable () {// submit it to @ overridepublic void run () {toast through a common handler thread and UI thread. maketext (getapplicationcontext (), "Stop Service", toast. length_long ). show () ;}}); super. ondestroy ();}/*** this method must be executed. It is useful when the bind method is used to start the service. * // @ Overridepublic ibinder onbind (intent) {// todo auto-generated method stubreturn mbinder;}/*** class used for the client binder. because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */public class hellobinder extends binder {helloservice getservice () {return helloservice. this ;}} public void shownumber () {New thread (New runnable () {int I = 1; @ overridepublic void run () {While (true) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (I ++ );}}}). start ();}}

Helloserviceactivity. Java

Package HB. android. service; import HB. android. service. helloservice. hellobinder; 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. view. view. onclicklistener; import android. widget. button; import android. widget. textview; public class helloserviceactivity extends activity {intent; Boolean flag = true; helloservice mservice; Boolean mbound = false; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); intent = new intent (); initmywidget (); setmywidgetlistener ();} public void setmywidgetlistener () {mywidget. btn_bind.setonclicklistener (New widgetonclicklistener (); mywidget. btn_start.setonclicklistener (New widgetonclicklistener (); mywidget. btn_stop.setonclicklistener (New widgetonclicklistener (); mywidget. btn_unbind.setonclicklistener (New widgetonclicklistener (); mywidget. btn_kill.setonclicklistener (New widgetonclicklistener ();} class widgetonclicklistener implements onclicklistener {@ overridepublic void onclick (view v) {Switch (v. GETID () {case R. id. btn_start: intent. setclass (getapplicationcontext (), helloservice. class); intent. putextra ("test", "Start"); startservice (intent); flag = true; mywidget. btn_stop.setenabled (FLAG); break; case R. id. btn_stop: intent. putextra ("test", "stop"); stopservice (intent); flag = false; mywidget. btn_stop.setenabled (FLAG); break; case R. id. btn_kill: Android. OS. process. killprocess (Android. OS. process. mypid (); break; case R. id. btn_bind: intent = new intent (getapplicationcontext (), helloservice. class); bindservice (intent, mconnection, context. bind_auto_create); // automatically calls the oncreate Method System in the service. out. println ("BIND:" + mservice); opeservice (); break; case R. id. btn_unbind: If (mbound) {unbindservice (mconnection); // automatically call the ondestory method of the Service mbound = false;} break; default: break;} public void opeservice () {system. out. println ("opeservice:" + mservice); // mservice. shownumber () ;}} public void initmywidget () {mywidget. btn_bind = (button) findviewbyid (R. id. btn_bind); mywidget. btn_start = (button) findviewbyid (R. id. btn_start); mywidget. btn_stop = (button) findviewbyid (R. id. btn_stop); mywidget. btn_unbind = (button) findviewbyid (R. id. btn_unbind); mywidget. TV _test = (textview) findviewbyid (R. id. TV _test); mywidget. btn_kill = (button) findviewbyid (R. id. btn_kill);} Private Static class mywidget {static button btn_start; static button btn_stop; static button btn_bind; static button btn_unbind; static button btn_kill; @ suppresswarnings ("UNUSED ") static textview TV _test;} @ overrideprotected void ondestroy () {super. ondestroy (); stopservice (intent);}/** defines callbacks for Service binding, passed to bindservice () */private serviceconnection mconnection = new serviceconnection () {public void onserviceconnected (componentname classname, ibinder Service) {// We 've bound to LocalService, cast the ibinder and get LocalService instance hellobinder binder = (hellobinder) service; mservice = binder. getservice (); system. out. println ("serviceconnection:" + mservice); mbound = true; mservice. shownumber () ;}@ override public void onservicedisconnected (componentname arg0) {mbound = false ;};@ override protected void onstop () {super. onstop (); If (mbound) {unbindservice (mconnection); mbound = false ;}};}

Note: After a service is created, onserviceconnected establishes a connection with servicer.

After activit starts the service with bindservice:

Public serviceconnection mconnection = new serviceconnection () {@ overridepublic void onservicedisconnected (componentname name) {system. out. println ("onserviceconnected"); mbound = false;}/*** collect some methods to establish a connection between Serivce and activity after the service is created */@ overridepublic void onserviceconnected (componentname name, ibinder Service) {system. out. println ("onservicedisconnected"); mbound = true; localbinder mybinder = (localbinder) Ser Vice; myservice = mybinder. getservice (); // you can operate the service below. Myservice. shownumber ();}};

Control the Bound Service (connection and destruction)

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.