Monday 11 February 2013

WHAT IS SERVICE CONCEPT IN ANDROID WITH AND SIMPLE EXAMPLE


ANDROID SERVICE LIFE CYCLE EXPLANATION WITH AN EXAMPLE


  • A SERVICE is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.
  • A android component (for example Activity ) can also bind a service to it . It means the service will be continues its execution till components will be in running possition .
    For ExampleIf we are binding a service to an anctiviy then the service continues untill the activity destroy.
  • Components can communicate with the Service using interprocess communication (IPC).  
    For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.


Types of Service :-
Service can be classified of two types :-
  1. Started Service
  2. Bound Service

1-Started Service-
  • A service is "started" when an application component (such as an activity) starts it by calling startService().
  • This service can run in the background indefinitely, 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.
    Example - it might download or upload a file over the network. When the operation is done, the service should stop itself.
1-Bound Service-
  • A service is "bound" when an application component binds to it by calling  bindService().
    A bound service   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.






SERVICE LIFE CYCLE :-

These are the main callback method in Service life cycle -
  • onStartCommand()
    This method calls when the service is started by calling startService(). (In case of StartedService )
  • onBind()
    This method called when the service is started by calling bindService() . (in case of Bound Service).
  • OnCreate()
    This method called when the service is creating very first time.
  • OnStart()
    This is method called when the service is about to start .
  • Ondestroy()
    This method is called when the service is about to destroy.


This is an graphical representation of Service life cycle :-



SIMPLE EXAMPLE OF SERVICE (StartedService OR Unbind Service) TO UNDERSTAND ITS WORKING

  • Step 1 – Create a class name Service_Example and copy past the following code
public class Service_Example extends Activity {

Button start,stop;
Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_service__example);
start=(Button)findViewById(R.id.start);
stop=(Button)findViewById(R.id.stop);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
i=new Intent(Service_Example.this,MyService.class);
startService(i);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(i);
}
});
}
}

  • Step 2– Create a class name MyService and copy past the following code


public class MyService extends Service {


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this,"service StartedCOmmand method",Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
// TODO Auto-generated method stub

Toast.makeText(this,"service is created",Toast.LENGTH_SHORT).show();
super.onCreate();
}


@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this,"service is Started",Toast.LENGTH_SHORT).show();
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this,"service is destroyed",Toast.LENGTH_SHORT).show();
}
}


  • Step 3– Copy the following code in Manifest File.
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service_example"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Service_Example"
android:label="@string/title_activity_service__example" >
<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>

  • Step 4– This is the layout file (activity_service__example) code for your Service_example Activity .

<?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"
>
<Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start Service "
/>
<Button
android:id="@+id/stop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop Serivce"
/>

</LinearLayout>




Example of BIND SERVIE IN ANDRID

In Bind Service you need to Override one more method in your service class and the method syntax as follows -


@Override
  public IBinder onBind(Intent intent) {
  //TODO for communication return IBinder implementation
    return null;
  }
Now Start Service by call bindService() method of Context Class as follows
                    bindService(intent,null,flag);


CLASSS USED FOR CREATING SERVICE IN ANDROID
There are two main classes used for creating Service :-
  • Service
  • IntentService
Service Class -
This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running.

IntentService -
  • This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. 
  • This is the best option if you don't require that your service handle multiple requests simultaneously.
  • Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.

1 comment: