Android Service And Its LifeCycle


Service is one of the main building block or component of android application , Service component is potentially is used to perform repetitive and long running task or operation in background without interacting with user interface and it doesn't poses any user interface and it's own life cycle which is independent of activity life cycle .



Service Life Cycle


The above diagram represents a typical life cycle of android service component .

Service Class Method


When your class extends service class you must override the following methods .

Method Description
  onCreate()
  •  This method gets executed by calling startService() method from another component like activity .
  • This method is executed only once during the service creation.
 onStartCommand() 
  • This method gets executed by calling startService() method from another component like activity.
  • once this method is called the service gets started in background and runs infinitely .
  onDestroy()
  • If the service is in running state a call to this method will stop the service from running .

Service Behaviour


The onStartCommand method of service class returns an int type which defines the behaviour of service with the android system , that is how should your service behave to the android system when it gets killed , So Service class provides three static integer constants. .

Return Constant Description
  Service.START_STICKY
If the service is got killed by the platform then restart the service without intent data.
  Service.START_NOT_STICKY
If the service is got killed by the platform then don't    restart,  if you want to start then you must explicitly make a call to startCommand().

  Service.START_REDELIVER_INTENT  
If the service is got killed by the platform then restart the service with intent data.


Service Declaration


Declare the service component in android manifest file inside the <application>  tag  with <service> tag by specifying it's name (android:name) as shown below.

<manifest ... >
  ...
  <application ... >
      <service
android:name=".ExampleService" />
      ...
  </application>
</manifest>

Lets See a sample example

Layout

file : activity_main.xml
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context="com.pavan.androidservice.MainActivity" >

    <Button

        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onstartClick"
        android:text="Start Service" />

    <Button

        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:onClick="onstopClick"
        android:text="Stop Service" />

</LinearLayout>

Service

file : MyService.java
package com.pavan.androidservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    public static final String TAG = MyService.class.getSimpleName();

    @Override
    public
IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public
void onCreate() {
        super.onCreate();

        Log.d(TAG, "onCreate method is called");

    }

    @Override
    public int
onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "onStartCommand method is called");

        return Service.START_NOT_STICKY;
    }

    @Override
    public void
onDestroy() {
        super.onDestroy();

        Log.d(TAG, "onDestroy method is called");
    }

}


Activity

file : MainActivity.java
package com.pavan.androidservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

    Intent mInent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mInent = new Intent(getApplicationContext(), MyService.class);

    }

    public void onstartClick(View view) {

        startService(mInent);

    }

    public void onstopClick(View view) {

        stopService(mInent);

    }

}


Manifest

file : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest 

    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pavan.androidservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk

        android:minSdkVersion="16"
        android:targetSdkVersion="16" />

    <application

        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity

            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action
android:name="android.intent.action.MAIN" />

                <category
android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
android:name=".MyService" >
        </service>
    </application>

</manifest>

Logcat




Don't Miss : Communicating with Service through Broadcast Receiver.

In the next upcoming tutorial we will see different kinds of services in android like
  1. BindService.
  2. IntentService.

1 comment:

liễu nguyễn said...

Please help me ! when we use Unbound Service ? and Can Activity sent message to Unbound Service ? thks ! :)

Post a Comment