Android Service Example + Implementation

By Sanjeev K. Saroj, 02 April,2017  

In this article we will discuss about different android services with examples. We will discuss about what is Service, different types of services like Bounded, Unbounded and IntentService and how to implement different services in android along with the different concepts involved in android services.

What is Service in android

Android Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC).

For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background. This is basically a Base Class for all Services.By default, a service runs in the same process as the main thread of the application.

Therefore, you need to use asynchronous processing in the service to perform resource intensive tasks in the background. A commonly used pattern for a service implementation is to create and run a new Thread in the service to perform the processing in the background and then to terminate the service once it has finished the processing.

android-services

Types of services in Android

Bounded Service: Bounded service is used to perform background task in bound with another component.Bounded Service gets starts by calling bindService().Bounded Service is unbind or destroyed by calling unbindService(). Bound Service is dependent on the component in which it is started.

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).

Steps to create Bounded Service

Step 1: create an empty project in Android Studio.

create a class BoundedService which extends Service class. As we know if you want to create a service we need to extend from service class.

public class BoundedService extends Service { }

Step 2:Next we override onBind() method which we implement when we create our bound service.

public IBinder onBind(Intent intent) { return myBinder; }

Step 3:Now let's create the bound service by extending the binder class.

So, first of all, we will create a class inside our my service class which will be a public class and I will name it as MyLocalBinder. And this class will extend from the binder class and in this class we want to do is to create a method which returns Boundedservice and the method name is getService(). And what this is going to do is it is going to return an instance of Boundedservice.this.

public class MyLocalBinder extends Binder { BoundedService getService() { return BoundedService.this; } }

Step 4:We need to override methods of ServiceConnection

android.content.ServiceConnection is an interface which is used to monitor the state of service. We need to override following methods.

onServiceConnected(ComponentName name, IBinder service);

This is called when service is connected to the application.

//This is called when service is disconnected. onServiceDisconnected(ComponentName name);

We will be following this step in the Mainactivity class.

Step 5:In this step we are going to bind the service and start service using this code:

bindService(service, myconnection, Context.BIND_AUTO_CREATE); isBound = true; startService(service);

Step 6:And finally we are going to unbind the service using this

unbindService(myconnection);

Step 7:And finally declare your service in AndroidMenifest file.

<service android:name = ".BoundedService"></service>

UnBounded Service

Unbounded Service is used to perform long repetitive task. Unbound Service gets starts by calling startService().Unbound Service is stopped or destroyed explicitly by calling stopService().Unbound Service is independent of the component in which it is started.It is a kind of service which runs in the background indefinitely, even if the activity which started this service ends.

A service is started when an application component (such as an activity) calls startService(). After it's started, a 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. For example, it can download or upload a file over the network. When the operation is complete, the service should stop itself.

Steps to create Unbounded Service

Create a class UnBoundedService which extends Service class. As we know if you want to create a service we need to extend from service class.In your implementation, you must override some callback methods that handle key aspects of the service lifecycle and provide a mechanism that allows the components to bind to the service, if appropriate. These are the most important callback methods that you should override.

onStartCommand():The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is complete by calling stopSelf() or stopService(). If you only want to provide binding, you don't need to implement this method.

public int onStartCommand(Intent intent, int flags, int startId) { if(!mp.isPlaying()){ mp.start(); } return START_STICKY; }

So the Service might be terminated by the runtime incase there are too many processes running on the system or by a stopService() call. The second argument passed to onStartCommand() and the return value of onStartCommand() states what should happen after the Service is terminated, i.e., the restart behaviour. Let’s examine the different values:

START_STICKY: Service will be restarted if it gets terminated whether any requests are pending or not. The Intent of the earlier request passed (before termination) will not be resubmitted, instead null will be passed as Intent data. Hence use this option for Services that do not depend on Intent data to manage its state. All the pending requests are delivered with the START_FLAG_RETRY as the second argument (can also get using Intent.getFlags()).

START_NOT_STICKY: – Service is only restarted for pending requests. The Intent data specified while making the startService() calls will be passed.

START_REDELIVER_INTENT – Similar to START_STICKY and will receive both pending and started requests. The pending requests are delivered with the START_FLAG_RETRY flag set in the second argument whereas previously started requests are redelivered with the START_FLAG_REDELIVERY flag set. Also the original Intent is re-delivered.

onBind():The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null.

public IBinder onBind(Intent arg0) { return null; }

onCreate():The system invokes this method to perform one-time setup procedures when the service is initially created (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.

public void onCreate() { super.onCreate(); mp = MediaPlayer.create(getApplicationContext(), R.raw.song); }

onDestroy():The system invokes 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, or receivers. This is the last call that the service receives.

public void onDestroy() { mp.release(); super.onDestroy(); }

Note:Declare your service in AndroidMenifest file.

<service android:name = ".UnBoundedService"></service>

What is IntentService

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

Intent Service is used to perform one time task i.e when the task completes the service destroys itself .Intent Service gets starts by calling startService().IntentService Implicitly calls stopself() to destroy.Intent Service is independent of the component in which it is started.

Steps to create IntentService

Create a class MyIntentService which extends IntentService . You should add a constructor with the name of your service class. You will need to implement just one other method called onHandleIntent(). This method is where your processing occurs. Any data necessary for each processing request can be packaged in the intent extras, like so (imports, comments, exception handling removed for code clarity, see the code for details.

public class MyIntentService extends IntentService { MediaPlayer mp; public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { mp = MediaPlayer.create(getApplicationContext(), R.raw.song); mp.start(); } }

Note:At last, declare your service in AndroidMenifest file.

<service android:name = ".MyIntentService"></service>

Android Service Implementation

Following is the project structure.

android-service-project-strct

Create a empty project in Android Studio.Create a class MainActivity

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.devglan.serviceinandroid.MainActivity"> <Button android:id="@+id/btn_play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="PlayService" android:textAllCaps="false"/> <Button android:layout_below="@+id/btn_play" android:id="@+id/btn_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="StopService" android:textAllCaps="false"/> <Button android:layout_toRightOf="@+id/btn_play" android:id="@+id/btn_playIntent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="PlayIntentService" android:layout_marginLeft="20dp" android:textAllCaps="false"/> <Button android:layout_below="@+id/btn_playIntent" android:id="@+id/btn_stopIntent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="StopIntentService" android:layout_toRightOf="@+id/btn_play" android:layout_marginLeft="20dp" android:textAllCaps="false"/> <Button android:id="@+id/btn_playbounded" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="PlayBoundedService" android:textAllCaps="false" android:layout_below="@+id/btn_stop"/> <Button android:layout_below="@+id/btn_playbounded" android:id="@+id/btn_stopbounded" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="StopBoundedService" android:textAllCaps="false"/> </RelativeLayout>

This activity is basically to interact with user.In this activity we call all three services

MainActivity.java
import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button play, stop,btn_playIntent,btn_stopIntent,btn_playbounded,btn_stopbounded; private boolean isBound; BoundedService boundedService; private ServiceConnection myconnection; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); play = (Button) findViewById(R.id.btn_play); stop = (Button) findViewById(R.id.btn_stop); btn_playIntent = (Button) findViewById(R.id.btn_playIntent); btn_stopIntent = (Button) findViewById(R.id.btn_stopIntent); btn_playbounded = (Button) findViewById(R.id.btn_playbounded); btn_stopbounded = (Button) findViewById(R.id.btn_stopbounded); isBound = false; play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent service = new Intent(MainActivity.this, UnBoundedService.class); startService(service); } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent name = new Intent(MainActivity.this, UnBoundedService.class); stopService(name); } }); btn_playIntent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent service = new Intent(MainActivity.this, MyIntentService.class); startService(service); } }); btn_stopIntent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Can't stop Intent Service", Toast.LENGTH_SHORT).show(); } }); myconnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { boundedService = ((BoundedService.MyLocalBinder) iBinder).getService(); isBound = true; } @Override public void onServiceDisconnected(ComponentName componentName) { isBound = false; } }; btn_playbounded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent service = new Intent(MainActivity.this, BoundedService.class); if(!isBound) { bindService(service, myconnection, Context.BIND_AUTO_CREATE); isBound = true; startService(service); }else { unbindService(myconnection); isBound = false; } } }); btn_stopbounded.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent objIntent = new Intent(MainActivity.this, BoundedService.class); if(isBound) { isBound = false; unbindService(myconnection); stopService(objIntent); } else{ stopService(objIntent); } } }); } @Override protected void onDestroy() { super.onDestroy(); if (isBound) { unbindService(myconnection); isBound = false; } } }

Bounded Service Implementation

BoundedService.java
import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.media.MediaPlayer; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; /** * Created by sanjeevksaroj on 11/3/17. */ public class BoundedService extends Service { MediaPlayer mp; @Override public void onCreate() { super.onCreate(); mp = MediaPlayer.create(getApplicationContext(), R.raw.song); } @Override public int onStartCommand(Intent intent, int flags, int startId) { mp.start(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); mp.stop(); mp.release(); } public class MyLocalBinder extends Binder { BoundedService getService() { return BoundedService.this; } } private final IBinder myBinder = new MyLocalBinder(); @Nullable @Override public IBinder onBind(Intent intent) { return myBinder; } }

UnBounded Service Implementation

UnBoundedService.java
import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; /** * Created by sanjeevksaroj on 11/3/17. */ public class UnBoundedService extends Service { MediaPlayer mp; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); mp = MediaPlayer.create(getApplicationContext(), R.raw.song); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(!mp.isPlaying()){ mp.start(); } return START_STICKY; } @Override public void onDestroy() { mp.release(); super.onDestroy(); } }

IntentService Implementation

MyIntentService.java
package com.devglan.serviceinandroid; import android.app.IntentService; import android.content.Intent; import android.media.MediaPlayer; /** * Created by sanjeevksaroj on 11/3/17. */ public class MyIntentService extends IntentService { MediaPlayer mp; public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { mp = MediaPlayer.create(getApplicationContext(), R.raw.song); mp.start(); } }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.devglan.serviceinandroid"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyIntentService"></service> <service android:name=".UnBoundedService"></service> <service android:name=".BoundedService"></service> </application> </manifest>

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download the source

References:

Android Developer Bound Services

Suggest more topics in suggestion section or write your own article and share with your colleagues.

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.

Further Reading: