Basics Of Services In Android - Part 1

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  theofficial 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 internet in background, fetching Contacts etc.

A Service can take forms are as follows :

  • Started Services
  • Bound Services
Started Services

Started Services are 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 stops 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 the we can communicate with the service through activity and vice versa is also true. A 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 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 but 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.   
  13.     <Button  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="Start service "  
  17.         android:id="@+id/start_services_button"  
  18.         android:layout_alignParentTop="true"  
  19.         android:layout_centerHorizontal="true"  
  20.         android:layout_marginTop="65dp"/>  
  21.   
  22.     <Button  
  23.         android:layout_width="wrap_content"  
  24.         android:layout_height="wrap_content"  
  25.         android:text="Stop Service"  
  26.         android:id="@+id/stop_service_button"  
  27.         android:layout_below="@+id/start_services_button"  
  28.         android:layout_centerHorizontal="true"  
  29.         android:layout_marginTop="45dp" />  
  30.   
  31. </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.   
  27.     @Override  
  28.     protected void onStart() {  
  29.         // TODO Auto-generated method stub  
  30.         /**Starting service from button click **/  
  31.   
  32.         super.onStart();  
  33.     }  
  34.   
  35.     @Override  
  36.     protected void onStop() {  
  37.         // TODO Auto-generated method stub  
  38.   
  39.         super.onStop();  
  40.     }  
  41.   
  42.     @Override  
  43.     public void onClick(View v) {  
  44.         switch (v.getId()) {  
  45.             case R.id.start_services_button:  
  46.                 intent = new Intent(this,  
  47.                         MyService.class);  
  48.                 startService(intent);  
  49.                 break;  
  50.   
  51.             case R.id.stop_service_button:  
  52.                 stopService(intent);  
  53.   
  54.                 break;  
  55.             default:  
  56.                 break;  
  57.         }  
  58.   
  59.     }  
  60.   
  61. }  
Step 3:

Lets 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 gets 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 call of this method all the computation will be started as shown in figure below. As we can see that after full computation up to generation of number up to 9 and then serviceis 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 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:

Up Next
    Ebook Download
    View all
    Learn
    View all