Saturday, July 30, 2011

Service LifeCycle

A service is an application component that can run some long running task in the background without the need for a user interface. Some other application component can start the service and this service will then keep on running even if the user switches to another application.

A service can essentially take two forms:


Unbounded
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 (unbounded), even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.


Bound
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). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.



As you can see in diagram there some method in  Unbounded service class for life cycle :


startService(Intent Service)
This you must call to start un-bounded serviec

onCreate()
This method is Called when the service is first created

onStartCommand(Intent intent, int flags, int startId)
This method is called when service is started

onBind(Intent intent)
This method you must call if you want to bind with activity

onUnbind(Intent intent)
This method is Called when the service will un-binded from activity

onRebind(Intent intent)
This method is called when you want to Re-bind service after calling un-bind method

onDestroy()
This method is called when The service is no longer used and is being destroyed


Let's create a small app to understand this..

-------------------------------------------
App Name: ServiceLifeCycle
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------

MyActivity.java

package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MyActivity extends Activity 
                    implements OnClickListener {
	private final static String TAG = "In this method: ";
	private Button startSerivce = null;
	private Button stopSerivce = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		startSerivce = (Button) findViewById(R.id.buttonStart);
		startSerivce.setOnClickListener(this);
		stopSerivce = (Button) findViewById(R.id.buttonStop);
		stopSerivce.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (startSerivce == v) {
			Log.i(TAG, "Activity starting service..");
			Intent serviceIntent = new Intent(this, MyService.class);
			startService(serviceIntent);
		} else {
			Intent in = new Intent(this, MyService.class);
			in.setAction("stop");
			stopService(in);
		}
	}
}

MyService
package com.rdc;

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

public class MyService extends Service {

	private final static String TAG = "In this method: ";
	int mStartMode; // indicates how to behave if the service is killed
	IBinder mBinder; // interface for clients that bind
	boolean mAllowRebind; // indicates whether onRebind should be used

	@Override
	public void onCreate() {
		Log.i(TAG, "Service created");
		// The service is being created
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "Service started");
		
		Toast.makeText(getBaseContext(), "Service has been started..",
				Toast.LENGTH_SHORT).show();
		return mStartMode;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// A client is binding to the service with bindService()
		Log.i(TAG, "Service binded");
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// All clients have unbound with unbindService()
		Log.i(TAG, "Service un-binded");
		return mAllowRebind;
	}

	@Override
	public void onRebind(Intent intent) {
		// A client is binding to the service with Re-bindService(),
		// after onUnbind() has already been called
		Log.i(TAG, "Service re-binded");
	}

	@Override
	public void onDestroy() {
		// The service is no longer used and is being destroyed
		Log.i(TAG, "Service destroyed");

	}

}


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:gravity="center">
	<LinearLayout
		android:layout_height="wrap_content"
		android:layout_width="match_parent"
		android:id="@+id/linearLayout1"
		android:gravity="center">
		<Button
			android:layout_height="wrap_content"
			android:layout_width="wrap_content"
			android:id="@+id/buttonStart"
			android:text="Start Service"></Button>
		<Button
			android:layout_height="wrap_content"
			android:layout_width="wrap_content"
			android:id="@+id/buttonStop"
			android:text="Stop Serivce"></Button>
	</LinearLayout>
</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.rdc"
	android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="8" />

	<application
		android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity
			android:name=".MyActivity"
			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:enabled="true"
			android:name=".MyService">
			<intent-filter>
			<action android:name="com.rdc.MyService">
			</action>
			</intent-filter>
		</service>

	</application>
</manifest>

The output Screen will be like this..



You can download the complete source code zip file here : ServiceLifeCycle

Cheers!!

I'd love to hear your thoughts!

No comments:

Post a Comment