Android: Service

Source: Internet
Author: User
Tags call back hosting
Public abstract class

Service

Extends contextwrapper
Implements componentcallbacks class overview

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'sAndroidManifest.xml. Services can be startedContext.startService()AndContext.bindService().

 

Service is mainly used for two purposes:

1. Execute a task in the backend for a long time and do not directly interact with users

2. provide some functional services to other applications

 

Note that services, like other application objects, run in the main thread of their hosting process. this means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it shoshould spawn its own thread in which to do that work. more information on this can be found in Application Fundamentals: Processes and threads. theIntentServiceClass is available as a standard implementation of service that has its own thread where it schedules its work to be done.

The service class is an important part of an application's overall lifecycle.

 

 

Topics covered here:

  1. What is a service?
  2. Service Lifecycle
  3. Permissions
  4. Process Lifecycle
  5. Local Service Sample
  6. Remote Messenger Service Sample
What is a service?

Most confusion about the service class actually revolves around what it isNot:

  • A service isNotA separate process. The service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part.
  • A service isNotA thread. It is not a means itself to do work off of the main thread (to avoid application not responding errors ).

Service is not an independent process, but a process where the application is located. Service is not a thread either.

 

Thus a service itself is actually very simple, providing two main features:

  • A facility for the application to tell the systemAboutSomething it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calltoContext.startService(), Which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
  • A facility for an application to expose some of its functionality to other applications. This corresponds to calltoContext.bindService(), Which allows a long-standing connection to be made to the Service in order to interact with it.

When a service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call itsonCreate()And any other appropriate callbacks on the main thread. It is up to the service to implement these with the appropriate behavior, such as creating a secondary thread in which it does its work.

Note that because service itself is so simple, you can make your interaction with it as simple or complicated as you want: from treating it as a local Java object that you make direct method callon (as partitioned strated by local service sample), to providing a full remoteable interface using aidl.

 

 

Service Lifecycle

There are two reasons that a service can be run by the system. If someone CILSContext.startService()Then the system will retrieve the Service (creating it and calling itsonCreate()Method if needed) and then call itsonStartCommand(Intent, int, int)Method with the arguments supplied by the client. The service will at this point continue runningContext.stopService()OrstopSelf()Is called. note that multiple callto context. startservice () do not nest (though they do result in multiple corresponding callto onstartcommand (), so no matter how many times it is started a service will be stopped once context. stopservice () or stopself () is called; however, services can use theirstopSelf(int)Method To ensure the service is not stopped until started intents have been processed.

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onstartcommand ():START_STICKYIs used for services that are explicitly started and stopped as needed, whileSTART_NOT_STICKYOrSTART_REDELIVER_INTENTAre used for services that shocould only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

Clients can also useContext.bindService()To obtain a persistent connection to a service. This likewise creates the service if it is not already running (callingonCreate()While doing so), but does not call onstartcommand (). The client will receiveIBinderObject that the service returns from itsonBind(Intent)Method, allowing the client to then make callback to the service. the Service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's ibinder ). usually the ibinder returned is for a complex interface that has been written in aidl.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is startedOrThere are one or more connections to it withContext.BIND_AUTO_CREATEFlag. Once neither of these situations hold, the Service'sonDestroy()Method is called and the service is already tively terminated. All cleanup (stopping threads, unregistering receivers) shocould be complete upon returning from ondestroy ().

 

Three methods of service call:

1. When the system calls context. when startservice (), the system will search for whether there is a proper service response. If yes, it will call its oncreate () function to create it, and then call its onstartcommand (), service will run until context appears. stopservice () or stopself.

2. The client code can also call context. bindservice () to obtain long-term binding with a service. This will also call the oncreate () method of the service, but will not call the onstartcommand () method. The client code will get an ibinder object. If it calls the onbind () method of the service, this allows the client to call back the service through the ibinder object. The Service will always run in the background, even if there is no client code to reference the Service's ibinder object.

3. The service can be enabled and bound at the same time. In this case, the service will remain running when it is enabled or when a connection is bound to the service. However, once both conditions are not met, the ondestroy () function of the Service will be called. Therefore, the ondestroy () function must be cleaned up, such as stopping related threads and canceling receivers)

 

Permissions

Global access to a service can be enforced when it is declared in its manifest's<service>Tag. By doing so, other applications will need to declare a corresponding<uses-permission>Element in their own manifest to be able to start, stop, or bind to the service.

In addition, a service can protect individual IPC callinto it with permissions, by callingcheckCallingPermission(String)Method Before executing the implementation of that call.

 

The <service> label must be added to the manifest file corresponding to the service, but the <uses-Permission> label must be used on the client that uses the service.

 

Process Lifecycle

The Android system will attempt to keep the process hosting a service around as long as the service has been started or has clients bound to it. when running low on memory and needing to kill existing processes, the priority of a process hosting the service will be the her of the following possibilities:

  • If the service is currently executing code in itsonCreate(),onStartCommand(), OronDestroy()Methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.

  • If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible. because only a few processes are generally visible to the user, this means that the Service shocould not be killed into T in extreme low memory conditions.

  • If there are clients bound to the service, then the Service's hosting process is never less important than the most important client. that is, if one of its clients is visible to the user, then the service itself is considered to be visible.

  • A started service can usestartForeground(int, Notification)API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the Service to be killed under extreme memory pressure from the current foreground application, but in practice this shocould not be a concern .)

Note This means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. if this happens, the system will later try to restart the service. an important consequence of this is that if you implementonStartCommand()To schedule work to be done asynchronously or in another thread, then you may be want to useSTART_FLAG_REDELIVERYTo have the system re-deliver an intent for you so that it does not get lost if your service is killed while processing it.

Other application components running in the same process as the service (such asActivity) Can, of course, increase the importance of the overall process beyond just the importance of the service itself.

 

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

Android. App. Service

 

Below are some common member methods:

 

Public void oncreate () since: API Level 1

Called by the system when the service is first created. Do not call this method directly

 

Public void ondestroy () since: API Level 1

Called by the system to invoke y a service that it is no longer used and is being removed. the service shoshould clean up an resources it holds (threads, registered receivers, etc) at this point. upon return, there will be no more callin to this service object and it is too tively dead. do not call this method directly.

 

Public int onstartcommand (intent, int flags, int startid) since: API Level 5

Called by the system every time a client explicitly starts the service by callingstartService(Intent), Providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.

For backwards compatibility, the default implementation CILSonStart(Intent, int)And returns eitherSTART_STICKYOrSTART_STICKY_COMPATIBILITY.

 

Parameters

Intent The intent suppliedstartService(Intent), As given. This may be null if the service is being restarted after its process has gone away, and it had previusly returned anything else tSTART_STICKY_COMPATIBILITY.
Flags Additional data about this start request. Currently either 0,START_FLAG_REDELIVERY, OrSTART_FLAG_RETRY.
Startid A unique integer representing this specific request to start. UsestopSelfResult(int).

 

 

Public abstract ibinder onbind (intent) since: API Level 1

Return the communication channel to the service. may return NULL if clients can not bind to the service. The returnedIBinderIs usually for a complex interface that has been described using aidl.

Note that unlike other application components, callon to the ibinder interface returned here may not happen on the main thread of the process. More information about this can be found in Application Fundamentals: Processes and threads.

 

Parameters
Intent The intent that was used to bind to this service, as givenContext.bindService. Note that any extras that were has ded with the intent at that point willNotBe seen here.
Returns
  • Return an ibinder through which clients can call on to the service.
Public final void stopself () since: API Level 1

Stop the service, if it was previusly started. This is the same as callingstopService(Intent)For this special service

 

 

The LocalService In the SDK has not been studied .....

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.