What is service in android?

A service is an application in Android that runs in the background without needing to interact with the user. As for example if you want to play music in background you can use service, if you want to collect gps data then you can use service. 
Hence you can say that service is used when there is no interaction of user needed. 
To create a service in android you have to extend Service base class. As for example

public class MyService extends Service {

}
Within the MyService class, you implemented three methods:

@Override
public IBinder onBind(Intent arg0) { ... }
@Override
public int onStartCommand(Intent intent, int flags, int startId) { ... }
@Override
public void onDestroy() { ... }

The onBind() method enables you to bind an activity to a service. This in turn enables an activity to directly access members and methods inside a service.

The onStartCommand() method is called when you start the service explicitly using the startService() method.

The onDestroy() method is called when the service is stopped using the stopService() method. This is where you clean up the resources used by your service.

All services that you have created must be declared in the AndroidManifest.xml  like this:

<service android:name=”.MyService” />

If you want your service to be available to other applications, you can always add an intent filter with 

an action name, like this:

<service android:name=”.MyService”>
<intent-filter>
<actionandroid:name=”com.packageName.MyService” />
</intent-filter>
</service>

No comments:

Post a Comment