Android Basic Training Course: The theory of Service

    A Service is a component which runs in the background without direct interaction with the user. As the Service has no user interface, it is not bound to the life cycle of an Activity.
    Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.

Why use Services?

    Service is the perfect choice for functions not required to directly access the Activity interface. E.g:
  •  Perform the activity should continue even if the user leaves the application's activity, such as long load (for example, to download an app from Android Market) or playing (for example, an application Android music)
  • Perform the activity should exist regardless of circumstances, such as maintaining a connection support chat in a chat application.
  • Provide a local API to control the remote API, such as may be provided by a web service.
  • Perform periodic work without the intervention of users, like scheduled tasks.
    Many applications do not need any server. Very few applications require more than one Service. However, the Service is a powerful tool in the toolbox of a developer's Android and Service functions is a topic that any Android developers qualified to perform well.

Service Life Cycle

    There is 2 states of a Service:
  •  Started: a Service is started when an application component, such as an activity, starts it by calling startService(). Once started, a Service can run in the background indefinitely, even if the component that started it is destroyed.
  • Bounded: a Service is bound when an application component binds to it by calling bindService(). A bound Service offers a client-server interface that allows components to interact with the Service, send requests, get results, and even do so across processes with interprocess communication (IPC).
    The Service cannot be stopped until all clients unbind it. The following diagram on the left shows the life cycle when the Service is created with startService() and the diagram on the right shows the life cycle when the Service is created with bindService():
    To create an Service, you make a Java class that extends the Service class or one of it's existing subclasses. The Service base class defines various callback methods and the most important are given below:
  • onStartCommand(): called when another component, such as an activity, requests that the service be started, by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopService().
  • onBind(): called when another component wants to bind with the Service (such as to perform RPC), by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the Service, by returning an IBinder instance. You must always implement this method, but if you don't want to allow binding, then you should return null.
  • onUnbind(): called when all clients have disconnected from a particular interface published by the Service.
  • onRebind(): called when new clients have connected to the Service, after it had previously been notified that all had disconnected in its onUnbind().
  • onCreate(): called  when the Service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the Service is already running, this method is not called.
  • onDestroy(): called when the Service is no longer used and is being destroyed. Your Service should implement this to clean up any resources such as threads, registered listeners, receivers,... This is the last call the Service receives.

Declaring in Manifest

    Finally, you need to add the Service to file your AndroidManifest.xml, let it be recognized as a Service available for use. It is simply one more element <service> as a child element of the application, provide android:name attribute to reference your Service class.
    For example, here is a manifest expression a <service>:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="devexchanges.info.downloadservice"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
           
        <service
             android:name="MyService"
             android:icon="@drawable/icon"
             android:label="@string/service_name" />
    </application>

Start a Service


    You can start a service from an activity or other application component by passing an Intent to startService(). The Android system calls the service’s onStartCommand() method and passes it the Intent.
    For example:
Intent intent = new Intent(this, DownloadService.class);
startService(intent);

Stop a running Service

    A service must be stopped itself by calling stopSelf() method, once it is finishes execution. However, you can also stop a service yourself by calling stopService() method.
    Invoking stopService() method will call onDestroy() in your service. You have to manually stop your operation being performed by your application. To do this in the above example, we have taken a boolean variable to control the execution of Service.

Conclusions

    I have just introduce some basic knowledge about Service in Android. To the next post, I will give some examples for each type of it - from creating to destroying. Though this post, I hope that you can learn the Service philosophy, it's life cycle and important methods.
    Reference to official docs:
- Service: http://developer.android.com/reference/android/app/Service.html
- Service guide: http://developer.android.com/guide/components/services.html

Share


Previous post
« Prev Post
Next post
Next Post »