Basics Of Services In Android - Part 1

Introduction

 
A Service is part and parcel of the Android system. A wide variety of applications use the services to make them robust and functional. According to the official definition provided by Android docs: "A Service is an application component that can perform long-running operations in the background and does not provide a user interface".
 
If a user changes to another application it might be running in the background until it performs a complete task. Service could be bound by any component of an application to perform inter-process communication (IPC).
 
Some of the examples are playing songs, network transactions, downloading a file from the internet in the background, fetching Contacts, etc.
 
A Service can take forms are as follows :
  • Started Services
  • Bound Services

Started Services

 
Started Services is said to be started by calling the method startService()from an activity say MainActivity.java. Then it will call the method onStartCommand()of service class. if a service is called through this method from Main Activity then service might be indefinite even if the application is closed or stops if task gets completed. for example, downloading a file from the internet and should stop after download.
 

BoundServices

 
Bound Services are said to be bound by calling bindService()from the MainActivity or any other activity of your choice. Using this we can communicate with the service through activity and vice versa is also true. Bidirectional communication is achieved from this method. An Activity is said to be client and Service created is said to be Server that is a client-server architecture is formed.
 
In this case, service is bound to activity, service runs until activity exists or application is running. On the contrary, Started Services run indefinitely even if the application gets closed.
 
Let's create a simple service and focus mainly on the first part, Started Services.
 
Step 1
 
First, create a UI from which we can start our service although you can start your service without showing any UI or design part here let's take two buttons.
 
For starting and stopping services manually in activity_main.xml,
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     xmlns:tools="http://schemas.android.com/tools"    
  4.     android:layout_width="match_parent"    
  5.     android:layout_height="match_parent"    
  6.     android:paddingBottom="@dimen/activity_vertical_margin"    
  7.     android:paddingLeft="@dimen/activity_horizontal_margin"    
  8.     android:paddingRight="@dimen/activity_horizontal_margin"    
  9.     android:paddingTop="@dimen/activity_vertical_margin"    
  10.     tools:context="com.example.gkumar.activityservicecomm.MainActivity">    
  11.         
  12.     <Button    
  13.         android:layout_width="wrap_content"    
  14.         android:layout_height="wrap_content"    
  15.         android:text="Start service "    
  16.         android:id="@+id/start_services_button"    
  17.         android:layout_alignParentTop="true"    
  18.         android:layout_centerHorizontal="true"    
  19.         android:layout_marginTop="65dp"/>    
  20.     
  21.     <Button    
  22.         android:layout_width="wrap_content"    
  23.         android:layout_height="wrap_content"    
  24.         android:text="Stop Service"    
  25.         android:id="@+id/stop_service_button"    
  26.         android:layout_below="@+id/start_services_button"    
  27.         android:layout_centerHorizontal="true"    
  28.         android:layout_marginTop="45dp" />    
  29.     
  30. </RelativeLayout>   
    Step 2
     
    Add the following code to the MainActivity.java,
    1. package com.example.gkumar.activityservicecomm;    
    2.     
    3. import android.content.Intent;    
    4. import android.support.v7.app.AppCompatActivity;    
    5. import android.os.Bundle;    
    6. import android.util.Log;    
    7. import android.view.View;    
    8. import android.widget.Button;    
    9. import android.widget.Toast;    
    10.     
    11. public class MainActivity extends AppCompatActivity implements View.OnClickListener {    
    12.     Button startServiceButton, stopServiceButton;    
    13.     Intent intent;    
    14.     
    15.     @Override    
    16.     protected void onCreate(Bundle savedInstanceState) {    
    17.         super.onCreate(savedInstanceState);    
    18.         setContentView(R.layout.activity_main);    
    19.         startServiceButton = (Button) findViewById(R.id.start_services_button);    
    20.         stopServiceButton = (Button) findViewById(R.id.stop_service_button);    
    21.         stopServiceButton.setOnClickListener(this);    
    22.         startServiceButton.setOnClickListener(this);    
    23.     
    24.     }    
    25.     
    26.     @Override    
    27.     protected void onStart() {    
    28.         // TODO Auto-generated method stub    
    29.         /**Starting service from button click **/    
    30.     
    31.         super.onStart();    
    32.     }    
    33.     
    34.     @Override    
    35.     protected void onStop() {    
    36.         // TODO Auto-generated method stub    
    37.     
    38.         super.onStop();    
    39.     }    
    40.     
    41.     @Override    
    42.     public void onClick(View v) {    
    43.         switch (v.getId()) {    
    44.             case R.id.start_services_button:    
    45.                 intent = new Intent(this,    
    46.                         MyService.class);    
    47.                 startService(intent);    
    48.                 break;    
    49.     
    50.             case R.id.stop_service_button:    
    51.                 stopService(intent);    
    52.     
    53.                 break;    
    54.             default:    
    55.                 break;    
    56.         }    
    57.     
    58.     }    
    59.     
    60. }  
    Step 3
     
    Let's create a MyService.javaclass in the same package by extending the Android's Service class.
     
    Add the following code to this class,
    1. import android.app.Service;    
    2. import android.content.Intent;    
    3. import android.os.IBinder;    
    4. import android.support.annotation.Nullable;    
    5. import android.util.Log;    
    6. import android.widget.Toast;    
    7.     
    8. /**  
    9.  * Created by gkumar on 4/11/2016.  
    10.  */    
    11. public class MyService extends Service {    
    12.     
    13.     private boolean isRunning = true;    
    14.     
    15.     @Nullable    
    16.     @Override    
    17.     public IBinder onBind(Intent intent) {    
    18.         return null;    
    19.     }    
    20.     @Override    
    21.     public void onCreate() {    
    22.         Toast.makeText(this"The new Service was Created", Toast.LENGTH_LONG).show();    
    23.     
    24.         Log.i("Services ::""Service onCreate");    
    25.     
    26.         isRunning = true;    
    27.     }    
    28.     @Override    
    29.     public int onStartCommand(Intent intent, int flags, int startId) {    
    30.         // TODO Auto-generated method stub    
    31.         Toast.makeText(this" Service Started", Toast.LENGTH_LONG).show();    
    32.     
    33.         Log.d("Services::""service started through OnStartCommand()");    
    34.         MyThread myThread = new MyThread();    
    35.         myThread.start();    
    36.         return super.onStartCommand(intent,flags,startId);    
    37.     }    
    38.     
    39.     public class MyThread extends Thread {    
    40.     
    41.         @Override    
    42.         public void run() {    
    43.             // TODO Auto-generated method stub    
    44.             for(int i=0; i<10; i++){    
    45.                 try {    
    46.                     Thread.sleep(3000);    
    47.     
    48.                 } catch (InterruptedException e) {    
    49.                     // TODO Auto-generated catch block    
    50.                     e.printStackTrace();    
    51.                 }    
    52.                 if(isRunning){    
    53.                     Log.d("Executing Services",String.valueOf(i));    
    54.                 }    
    55.             }    
    56.             stopSelf(); // after completion of task it stops automatically    
    57.         }    
    58.     
    59.     }    
    60.     
    61.     @Override    
    62.     public void onDestroy() {    
    63.         super.onDestroy();    
    64.         Toast.makeText(MyService.this,"Service Stopped",Toast.LENGTH_SHORT).show();    
    65.         isRunning=false;    
    66.         Log.d("service :","destroyed");    
    67.     }    
    68. }   
      Step 4
       
      Now, implementing is a very important part that is AndroidManifest.xml,
       
      Register a Service in the service tag by its name as shown in the following written code below.
      1. <?xml version="1.0" encoding="utf-8"?>    
      2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"    
      3.     package="com.example.gkumar.activityservicecomm">    
      4.     
      5.     <application    
      6.         android:allowBackup="true"    
      7.         android:icon="@mipmap/ic_launcher"    
      8.         android:label="@string/app_name"    
      9.         android:supportsRtl="true"    
      10.         android:theme="@style/AppTheme"    
      11.         >    
      12.     
      13.         <activity android:name=".MainActivity"    
      14.             android:screenOrientation="portrait">    
      15.             <intent-filter>    
      16.                 <action android:name="android.intent.action.MAIN" />    
      17.     
      18.                 <category android:name="android.intent.category.LAUNCHER" />    
      19.             </intent-filter>    
      20.     
      21.         </activity>    
      22.         <service android:name=".MyService"/>    
      23.     </application>    
      24.     
      25. </manifest>   
        Step 5
         
        Running Application
         
        Service started
         
        Click on the start button service to get started.
         
         
        Service stopped
         
        Click stop button service gets stopped and if you will not press service gets automatically destroyed.
         
         
        Analysis in LogCat
         
        When clicking on the start button the service gets started and first onCreate () method called of service and then onStartCommand(). After the call of this method, all the computations will be started as shown in the figure below. As we can see that after full computation up to the generation of number up to 9 and then service is stopped because we have called stopSelf() and destroyed because we have called onDestroy() as shown in code.
         
         

        Summary

         
        This article explains about a service in Android and how they started and how to interact with them with the help of buttons we created, although it is running in the background that's why we can't see it. In the next article, we will learn how to bind activity with services and communication between them.
         
        Read more articles on Android


        Similar Articles