As an Android beginner, it is often confusing to use the service. Today, with the Google API for one of the four components of service, the simple use of instructions.
I hope that the same beginners and I have the help, if there is no place, also want to point out in time. Service: is an application component that runs in the background for a long time without a user interface. Even if the user switches to another app, the service can still run in the background. In addition, a component can bind itself to the service, even interprocess communication. For example, a service can handle network requests, play music, process I/O operations, and interact with content provider. The above is the introduction of the API to the service, in short, the service is able to run in the background for a long time, do not need a component of the interface. The existence form of service, that is, there are two ways to start. Need to be started by intent. The 1,stared (boot) component starts the service by calling StartService (), and even if the component is destroyed, the service can still run in the background. Call StopService (), stopself () to destroy the service.StartService (serviceintent); StopService (serviceintent); The 2,bound (binding) component is started by calling Bindservice () and the service to bind. Service execution Onbind (). Unbind the service and components with Unbindservice (). The service executes Onunbind () when it is unbound, and then executes OnDestroy () if no component or service has a binding relationship at this time; A binding-initiated service provides a client-server (IBinder communication mechanism) that enables interaction between a component and a service. Multiple components can be bound to a service, and service execution Ondetroy () is destroyed when all components are unbound. PublicAbstractBooleanBindservice (Intent service, Serviceconnection Conn, intflags); PublicAbstractvoidUnbindservice (Serviceconnection conn);When booting by bound, you need to create a serviceconnetction and override the Onservicedisconnected,onserviceconnected method, This is the Client-server (IBinder communication) provided by the service. PrivateserviceconnectionConnection =Newserviceconnection () { @Override Publicvoid onservicedisconnected (componentname arg0) {Log. e (TAG,"onservicedisconnected"); } @Override Publicvoidonserviceconnected (componentname arg0, IBinderService) {Log. e (TAG,"onserviceconnected");MyService Mservice = ((MyService.mybinder) service). GetService (); } };In the Onbind () method of the service, you return a binder. Binders can be customized. For example: PublicIBinderMybinder=NewMybinder (); @Override Publicibinder onbind (Intent arg0) { //TODOauto-generated Method StubLog. e (TAG,"Onbind"); returnMybinder; } PublicclassMybinderextendsbinder{ PublicTestservice GetService () { returnTestservice. This; } }The binder returned in Onbind () can be obtained in onserviceconnected () so that it can get the service object and manipulate it.MyService Mservice = ((MyService.mybinder) service). GetService (); * * The communication mechanism on IBinder can be studied in depth. # #Service可以被启动多次, can also be bound multiple times, can also be both bound and started. ## service By default, is present in the main thread (UI thread) of the primary process, and the service does not create its own new thread, nor does it run in a different process. Unless a special statement is made to the service. This means that if you take some time-consuming or complex-intensive operations in the service, you should do so in a thread. # # Service If the started mode is started, and is bound mode start, at this time call StopService () is not able to destroy the service, only if the Unbind () off all bindings, to perform the service OnDestroy (); # # Service and Activity components, the use of the time required in the manifest declaration settings. You can set the service to private, or increase the setting parameters such as intent filter. Once the ok,service is started, focus on its life cycle. First way: StartService () onCreate () creating servi CE, this callback method is only executed once. The service starts multiple times and is not created more than once. onstartcommand () StartService () will be executed every time. For example, this method is executed after the service is created. Data can be passed through intent when the service is started. Processing is done in this method. OnDestroy () call StopService () stopself () or Unbind (), Line This method, the service is destroyed. Second Way Bindservice () oncreate () Create SE Rvice, this callback method is only executed once. Service MultiThe start time is not created more than once. Onbind () to bind service and callback Ibinder.onunbind () unbind OnDestroy () &NBSP ; Destroy ** description of the Onstartcommand () return value:
-
START_NOT_STICKY
-
The service is not re-created after the system kills the service. Unless there's a pending intents to restart the service.
-
START_STICKY
-
After the system kills the service, re-creates the service and executes Onstartcommand (), but does not pass the last intent, but the system will pass in an empty intent when the Onstartcommand () is re-executed.
-
START_REDELIVER_INTENT
-
After the system kills the service, recreate the service and execute Onstartcommand (). Incoming last received intent.
Intendservice also has a class,intentservice in Android. Public AbstractclassIntentserviceextendsService { Private volatileLooperMservicelooper; Private volatileServicehandlerMservicehandler;From the source can be seen, intentservice inherit from the service, but also have their own looper and handler. The Google Api says:
The IntentService does the following:
- Creates a default worker thread this executes all intents delivered to
onStartCommand() separate from your application ' s main thread.
- Creates a work queue this passes one intent at a time to your
onHandleIntent() implementation, so you never has to worry about multi -threading.
- Stops the service after all start requests has been handled, so you never has to call
stopSelf() .
- Provides default implementation of that
onBind() returns NULL.
- Provides a default implementation of that sends the intent to the work queue and then to
onStartCommand() your onHandleIntent() implementation.
intentservice main functions:you manage a sequence of work messages, and only one task is executed at a time, meaning that it does not support multitasking concurrency. There is no need to call stopself to stop the service, and when no task is executed, it stops itself. When you use it, you only need to implementOnhandleintent ().@Override protected voidOnhandleintent (Intent intend) { // TODOauto-generated Method Stub } * * Often see someone ask, how to ensure that the service is not killed. Personally think, not to be killed, from two points to consider. 1. Increase priority 2. After killing and then restarting to increase service priority, you can use Setforeground (true) to turn the service into a foreground run. Use the callback return value in Onstartcommand () to cause the service to kill and then restart.also saw the great God said to create a daemon, after the service was killed after the restart. I don't know much about that. The introduction of service is these, in-depth things, I do not know very well. It's a little messy. Everyone is welcome to criticize, learn from each other, and seek the great God education. my QQ:1921991896
Simple Introduction to Android service usage