Services In Android!


A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed. A service can essentially take two states :

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.

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 inter-process communication (IPC).


Life Cycle Of Service
A service has life cycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. 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 a service, you create a Java class that extends the Service base class or one of its existing subclasses. The service base class defines various callback methods and the most important are given below. You don't have to /need to implement all the callback methods. However, its important that you understand each one and implement those that ensure your app behaves the way you expect. 


onStartCommand()The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). If you implement this method, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService() methods.
onBind()The system calls this method when another component wants to bind with the service by calling bindService(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don't want to allow binding, then you should return null.
onUnbind()The system calls this method when all clients have disconnected from a particular interface published by the service.
onRebind()The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).
onCreate()The system calls this method when the service is first created using onStartCommand() or onBind(). This call is required to perform one-time set-up.
onDestroy()The system calls this method 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, etc.

package com.apprajapati.Service;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {

/** indicates how to behave if the service is killed */
int mStartMode;

/** interface for clients that bind */
IBinder mBinder;

/** indicates whether onRebind should be used */
boolean mAllowRebind;

/** Called when the service is being created. */
@Override
public void onCreate() {

}

/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return mStartMode;
}

/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}

/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {

}

/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy()
}
}

Services run on main thread of its hosting process, it won't create any separate thread or creates its own thread unless you specify. This means, if your service is doing CPU intensive work such as MP3 playback or networking, then you should consider creating a new thread to carry out that work. Using that, you will reduce the risk of ANR (Application Not Responding) errors and main thread will work normally to keep your UI active during the process.

For security of your app, always use explicit intent when starting or binding your Service, and do not declare intent filters for the service. Additionally, you can ensure that your service is available to only your app by setting exported attribute to false in manifest file.

When to use what and how? 


ServiceThreadIntentServiceAsyncTask
When to use ?Task with no UI, but shouldn't be too long. Use threads within service for long tasks.- Long task in general.

- For tasks in parallel use Multiple threads (traditional mechanisms)
- Long task usually with no communication to main thread.
(Update)- If communication is required, can use main thread handler or broadcast intents[3]

- When callbacks are needed (Intent triggered tasks). 
- Relatively long task (UI thread blocking) with a need to communicate with main thread.[3]

- For tasks in parallel use multiple instances OR Executor[1]
TriggerCall to method
onStartService()
Thread start() methodIntentCall to method execute()
Triggered From (thread)Any threadAny ThreadMain Thread (Intent is received on main thread and then worker thread is spawed)Main Thread
Runs On (thread)Main ThreadIts own threadSeparate worker threadWorker thread. However, Main thread methods may be invoked in between to publish progress.
Limitations /
Drawbacks
May block main thread- Manual thread management

- Code may become difficult to read
- Cannot run tasks in parallel.

- Multiple intents are queued on the same worker thread.
- one instance can only be executed once (hence cannot run in a loop) [2]

- Must be created and executed from the Main thread

Post a Comment

0 Comments