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

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. <Button
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="Start service "
  15. android:id="@+id/start_services_button"
  16. android:layout_alignParentTop="true"
  17. android:layout_centerHorizontal="true"
  18. android:layout_marginTop="65dp"/>
  19. <Button
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="Stop Service"
  23. android:id="@+id/stop_service_button"
  24. android:layout_below="@+id/start_services_button"
  25. android:layout_centerHorizontal="true"
  26. android:layout_marginTop="45dp" />
  27. </RelativeLayout>
    Step 2
    Add the following code to the MainActivity.java,
    1. package com.example.gkumar.activityservicecomm;
    2. import android.content.Intent;
    3. import android.support.v7.app.AppCompatActivity;
    4. import android.os.Bundle;
    5. import android.util.Log;
    6. import android.view.View;
    7. import android.widget.Button;
    8. import android.widget.Toast;
    9. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    10. Button startServiceButton, stopServiceButton;
    11. Intent intent;
    12. @Override
    13. protected void onCreate(Bundle savedInstanceState) {
    14. super.onCreate(savedInstanceState);
    15. setContentView(R.layout.activity_main);
    16. startServiceButton = (Button) findViewById(R.id.start_services_button);
    17. stopServiceButton = (Button) findViewById(R.id.stop_service_button);
    18. stopServiceButton.setOnClickListener(this);
    19. startServiceButton.setOnClickListener(this);
    20. }
    21. @Override
    22. protected void onStart() {
    23. // TODO Auto-generated method stub
    24. /**Starting service from button click **/
    25. super.onStart();
    26. }
    27. @Override
    28. protected void onStop() {
    29. // TODO Auto-generated method stub
    30. super.onStop();
    31. }
    32. @Override
    33. public void onClick(View v) {
    34. switch (v.getId()) {
    35. case R.id.start_services_button:
    36. intent = new Intent(this,
    37. MyService.class);
    38. startService(intent);
    39. break;
    40. case R.id.stop_service_button:
    41. stopService(intent);
    42. break;
    43. default:
    44. break;
    45. }
    46. }
    47. }
    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. * Created by gkumar on 4/11/2016.
    9. */
    10. public class MyService extends Service {
    11. private boolean isRunning = true;
    12. @Nullable
    13. @Override
    14. public IBinder onBind(Intent intent) {
    15. return null;
    16. }
    17. @Override
    18. public void onCreate() {
    19. Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
    20. Log.i("Services ::", "Service onCreate");
    21. isRunning = true;
    22. }
    23. @Override
    24. public int onStartCommand(Intent intent, int flags, int startId) {
    25. // TODO Auto-generated method stub
    26. Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
    27. Log.d("Services::", "service started through OnStartCommand()");
    28. MyThread myThread = new MyThread();
    29. myThread.start();
    30. return super.onStartCommand(intent,flags,startId);
    31. }
    32. public class MyThread extends Thread {
    33. @Override
    34. public void run() {
    35. // TODO Auto-generated method stub
    36. for(int i=0; i<10; i++){
    37. try {
    38. Thread.sleep(3000);
    39. } catch (InterruptedException e) {
    40. // TODO Auto-generated catch block
    41. e.printStackTrace();
    42. }
    43. if(isRunning){
    44. Log.d("Executing Services",String.valueOf(i));
    45. }
    46. }
    47. stopSelf(); // after completion of task it stops automatically
    48. }
    49. }
    50. @Override
    51. public void onDestroy() {
    52. super.onDestroy();
    53. Toast.makeText(MyService.this,"Service Stopped",Toast.LENGTH_SHORT).show();
    54. isRunning=false;
    55. Log.d("service :","destroyed");
    56. }
    57. }
      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. <application
      5. android:allowBackup="true"
      6. android:icon="@mipmap/ic_launcher"
      7. android:label="@string/app_name"
      8. android:supportsRtl="true"
      9. android:theme="@style/AppTheme"
      10. >
      11. <activity android:name=".MainActivity"
      12. android:screenOrientation="portrait">
      13. <intent-filter>
      14. <action android:name="android.intent.action.MAIN" />
      15. <category android:name="android.intent.category.LAUNCHER" />
      16. </intent-filter>
      17. </activity>
      18. <service android:name=".MyService"/>
      19. </application>
      20. </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