Laplayer (1) Analysis of------service

Source: Internet
Author: User

Service is an application component that runs in the background for a long time and does not provide an interface. Other components can start a service, and the service can continue to run in the background even if the user switches to another app. In addition, a component can set a service to its own, interact with it, and even perform interprocess communication (IPC). Therefore, in the development of the player, in order to play music does not depend on the specific activity, the play music control is placed in the service.

The service, like activity, needs to be configured in Androidmainfest.xml, configured as follows:

1         <Service2             Android:name= "Com.porco.service.PlayService" android:exported= "false">3             <Intent-filter>4                 <ActionAndroid:name= "Playservice" />5             </Intent-filter>6         </Service>        

The Android:exported property is set here. This is used to indicate whether the service can be called or interacted with by other application components: If set to true, it can be called or interacted with, otherwise it cannot. When set to False, only the component of the same application or an application with the same user ID can start or bind the service.
Its default value depends on the filters that are included with the service. The absence of a filter means that the service can only be invoked by specifying an explicit class name, which means that the service can only be used internally within the application (because other external users will not know the class name of the service), so the default value for this property is false in this case. On the other hand, if at least one filter is included, it means that the service can provide services to other external applications, so the default value is true, and in this case there is a warning message in Eclipse: exported service does not require Permission

There are two ways to use the service:Context.s in Tartservice () and Context.bindservice (). The life cycle is:

  Context.startservice () Start process:

Context.startservice (), OnCreate (), Onstartcommand (), Service running, Context.stopservice ()-> ; OnDestroy (), Service stop

If the service is not running, Android calls OnCreate () first and then calls Onstartcommand ();

If the service is already running, only Onstartcommand () is called, so a service's Onstartcommand method may be called repeatedly.

If the stopservice will be directly OnDestroy, if the caller is directly exiting without calling StopService, the service will be running in the background, The service can be shut down by StopService after the caller has started up again.

So the life cycle of calling StartService is: onCreate---OnStart (can be called multiple times)--OnDestroy

  Context.bindservice () Start process:

Context.bindservice (), OnCreate (), Onbind (), Service running, Onunbind (), OnDestroy () Service stop

Onbind () returns a Ibind interface instance to the client, Ibind a method that allows the client to callback the service, such as getting an instance of the services, running state, or other operations. This time the caller (context, for example, activity) is bound together with the service, the context exits, Srevice will call Onunbind->ondestroy exit accordingly.

So the lifetime of the call Bindservice is: onCreate---Onbind (one time, not multiple bindings)--onunbind--and ondestory.

Only OnStart can be called multiple times (through multiple StartService calls) during each turn-off of the service, and the other oncreate,onbind,onunbind,ondestory can only be called once in a life cycle.

In the specific use, can be divided into the following three kinds of situations:

1.startService start the service.

2.bindService start the service.

3.startService & Bindservice Start-up service.

To test the invocation and lifecycle of a service in different scenarios, write the test demo code as follows:

Activity section •:

 Public classPlayactivityextendsActivity {PrivateIntent intent=NewIntent ("TService"); PrivateButton Mbuttonbind; PrivateButton Mbuttonunbind; PrivateButton Mbuttonplay; PrivateButton Mbuttonstart; PrivateButton Mbuttonstop;        Testservice TService; Serviceconnection Conn=Newserviceconnection () {@Override Public voidonservicedisconnected (componentname name) {//TODO auto-generated Method StubLOG.D ("Activity1", "Service service Disconnected"); } @Override Public voidonserviceconnected (componentname name, IBinder service) {//TODO auto-generated Method Stub//System.out.println ("bind OK");LOG.D ("Activity1", "Service connnected"); TService=( (Testservice.mbinder) service). GetService ();        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.player); //Bindservice (Intent, Conn, bind_auto_create);Mbuttonbind=(Button) Findviewbyid (R.id.buttonbind); Mbuttonunbind=(Button) Findviewbyid (R.id.buttonunbind); Mbuttonplay=(Button) Findviewbyid (R.id.buttonserviceplay); Mbuttonstart=(Button) Findviewbyid (R.id.buttonstart); Mbuttonstop=(Button) Findviewbyid (r.id.buttonstop); Mbuttonbind.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubBindservice (Intent, Conn, bind_auto_create); LOG.D ("Activity1", "Activity after Bindservice");        }        }); Mbuttonunbind.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubUnbindservice (conn); LOG.D ("Activity1", "Activity after Unbindservice");                }        }); Mbuttonplay.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubTservice.play ();                }        }); Mbuttonstart.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubStartService (Intent); LOG.D ("Activity1", "Start service");                }        }); Mbuttonstop.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubStopService (Intent); LOG.D ("Activity1", "Stop Service");            }        }); }}

Service section:

 Public classTestserviceextendsService {PrivateThread Mthread; @Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method StubLOG.D ("service", "Onbind"); return NewMbinder (); }        classMbinderextendsbinder{ PublicTestservice GetService () {returnTestservice. This; }} @Override Public voidonCreate () {//TODO auto-generated Method Stub        Super. OnCreate (); LOG.D ("Service", "service create"); } @Override Public voidOnDestroy () {//TODO auto-generated Method Stub                Super. OnDestroy (); LOG.D ("Service", "service Destory"); } @Override Public BooleanOnunbind (Intent Intent) {//TODO auto-generated Method StubLOG.D ("service", "Service Unbind"); return Super. Onunbind (Intent); } @Override Public voidOnrebind (Intent Intent) {//TODO auto-generated Method Stub        Super. Onrebind (Intent); LOG.D ("Service", "service rebind"); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {        //TODO auto-generated Method StubLOG.D ("service", "service start"); return Super. Onstartcommand (Intent, flags, Startid); }         Public voidPlay () {LOG.D ("Service", "Service Play"); }        }

1.startService start service: Used to start a service to perform background tasks, do not communicate, stop the service using StopService. Click the button to invoke the StartService () method, and the output is as follows:

2.bindService Start Service: This method starts the service to communicate and stops the service using Unbindservice. Click the button to invoke the Bindservice () method, and the output is as follows:

3.startService & bindservice Start Service: Service will always run in the background while calling StopService and Unbindservice to stop services. The result of the output (one) is as follows:

Combined above, you can draw:

1. When the service is not started, either calling the StartService or the Bindservice method, the service's OnCreate () method is called first to create a service.

2. If the StartService method is called before the service is created, the service's Onstartcommand () method is triggered once per call, if the Bindservice method is called, if it is bound, The Onbind method of the service is no longer triggered.

3. If you want to destroy the service, you need to call the corresponding method: Startservice--stopservice, Bindservice--unbindservice,startservice & Bindservice--stopservice &unbindservice, the Ondestory method of the service is triggered.

  

Also, one thing to note is that after executing the Bindservice method, the execution of the next statement precedes the creation of the service, so you need to be aware of the use of the objects returned by binder to prevent errors. The operational relationships and situations of specific service and activity in the same process require follow-up learning.

Reference Documentation:

Android Service (i)--service

full summary of Service in Android

Laplayer (1) Analysis of------service

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.