articles

Home / DeveloperSection / Articles / Services in Android

Services in Android

Manoj Pandey1962 25-Feb-2015

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

Android service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers 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 (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 

<?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 and click Start Service button 

 Services in Android


after click Stop Service button

 

Services in Android


Updated 07-Sep-2019

Leave Comment

Comments

Liked By