---
title: "Services in Android"  
description: "In this article i am explaining about Service in ANdroid"  
author: "Manoj Pandey"  
published: 2015-02-25  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/1610/services-in-android  
category: "android"  
tags: ["android", "service"]  
reading_time: 3 minutes  

---

# Services in Android

A Service is an [application component](https://www.mindstick.com/interview/2574/define-activity-application-component) that can perform long-running operations in the background and does not provide a [user interface](https://www.mindstick.com/blog/302016/what-is-user-interface-and-what-are-its-benefits).\

Android service is a component that is used to perform operations on the background such as playing music, [handle network](https://www.mindstick.com/forum/161866/how-does-a-service-worker-intercept-and-handle-network-requests-using-the-fetch-event) [transactions](https://www.mindstick.com/forum/34047/how-to-use-transactions-sql-server), interacting [content providers](https://www.mindstick.com/forum/158888/what-is-the-purpose-of-content-providers-in-android) etc. It doesn't has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter process [communication](https://www.mindstick.com/articles/126321/5-fails-and-fixes-of-the-office-communication) (IPC).

##### There can be two forms of a service. The lifecycle of service can follow two

##### different paths: started or bound.

· Started

· Bound

##### Started Service

A service is started when component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.

##### Bound Service

A service is bound when another component calls bindService() method. The client can unbind the service by calling the unbindService() method.

Let's see the sample of service in android that plays an audio in the background. Audio will not be stopped even if you switch to another activity. To stop the audio, you need to stop the service.

1. Create an Android project

2. Add three button in activity_main.xml

```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    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=".MainActivity" >     <Button        android:id="@+id/btnStart"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20sp"        android:text="Start Service" />     <Button        android:id="@+id/btnStop"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20sp"        android:text="Stop Service" />     <Button        android:id="@+id/btnMove"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20sp"        android:text="Move to Next" /> </LinearLayout>
```

3. Create an xml file for another activity

```
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical" >     <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Second Activity" /> </LinearLayout>
```

4. Create a class MyService class and this class must be extended of Service. The android.app.Service is subclass of ContextWrapper class. Paste following code in MyService.class

```
    package com.example.androidservice;  import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.widget.Toast;  public class MyService extends Service { MediaPlayer mPlayer;   @Override public IBinder onBind(Intent intent) {  // TODO Auto-generated method stub  return null; }   @Override public void onCreate() {  Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();  // MediaPlayer playback control of audio/video files and streams is  // managed as a state machine.  mPlayer = MediaPlayer.create(this, R.raw.flourish);   mPlayer.setLooping(false); // Set looping  }  @Override public void onStart(Intent intent, int startid) {  Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();  // Starts or resumes playback.  mPlayer.start(); }  @Override public void onDestroy() {  Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();  // Starts or resumes playback.  mPlayer.stop(); }}
```

5. Add following code in MainActivity.class

```
package com.example.androidservice;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity { Button btnStart, btnStop, btnMove; @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  // define button from views  btnMove = (Button) findViewById(R.id.btnMove);  btnStart = (Button) findViewById(R.id.btnStart);  btnStop = (Button) findViewById(R.id.btnStop);  // btnStart button click listener  btnStart.setOnClickListener(new OnClickListener() {   @Override   public void onClick(View v) {    // TODO Auto-generated method stub    Intent intent = new Intent(MainActivity.this, MyService.class);    // If the startService(intent) method is called and the service    // is not yet running, the service object is created and the    // onCreate() method of the service is called.    startService(intent);   }  });  // btnStop button click listener  btnStop.setOnClickListener(new OnClickListener() {   @Override   public void onClick(View v) {    // TODO Auto-generated method stub    Intent intent = new Intent(MainActivity.this, MyService.class);    // You stop a service via the stopService() method.    stopService(intent);   }  });  // btnMove button click listener  btnMove.setOnClickListener(new OnClickListener() {   @Override   public void onClick(View v) {    // TODO Auto-generated method stub    Intent intent = new Intent(MainActivity.this,      OtherActivity.class);    // start a new activity    startActivity(intent);   }  }); } @Override public boolean onCreateOptionsMenu(Menu menu) {  // Inflate the menu; this adds items to the action bar if it is present.  getMenuInflater().inflate(R.menu.main, menu);  return true; }}
```

6. In the last add service in [AndroidManifest.xml file](https://www.mindstick.com/interview/2588/explain-androidmanifest-xml-file-in-detail)

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidservice"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <application        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.androidservice.MainActivity"            android:label="@string/app_name" >            <intent-filter>               
<action android:name="android.intent.action.MAIN"/>               
<category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>        </activity>
        <activity
android:name="com.example.androidservice.OtherActivity"/>
        <service            android:name="com.example.androidservice.MyService"            android:enabled="true" >        </service>    </application></manifest>
```

7.

Run [your application](https://answers.mindstick.com/qa/95487/how-do-you-troubleshoot-when-your-application-link-is-not-responding) and click Start Service button

![Services in Android](https://www.mindstick.com/mindstickarticle/a1b46027-7456-4c33-a2b1-764b27f09339/images/4838b96a-8f74-411c-9820-e53c4b0f380b.png)

\
after click Stop Service button

![Services in Android](https://www.mindstick.com/mindstickarticle/a1b46027-7456-4c33-a2b1-764b27f09339/images/8bb44096-e658-49f4-925c-72466aee5606.png)

---

Original Source: https://www.mindstick.com/articles/1610/services-in-android

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
