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
BoundServices
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout 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: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="com.example.gkumar.activityservicecomm.MainActivity">
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Start service "
- android:id="@+id/start_services_button"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="65dp"/>
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Stop Service"
- android:id="@+id/stop_service_button"
- android:layout_below="@+id/start_services_button"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="45dp" />
- </RelativeLayout>
- package com.example.gkumar.activityservicecomm;
- import android.content.Intent;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.Toast;
- public class MainActivity extends AppCompatActivity implements View.OnClickListener {
- Button startServiceButton, stopServiceButton;
- Intent intent;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- startServiceButton = (Button) findViewById(R.id.start_services_button);
- stopServiceButton = (Button) findViewById(R.id.stop_service_button);
- stopServiceButton.setOnClickListener(this);
- startServiceButton.setOnClickListener(this);
- }
- @Override
- protected void onStart() {
- // TODO Auto-generated method stub
- /**Starting service from button click **/
- super.onStart();
- }
- @Override
- protected void onStop() {
- // TODO Auto-generated method stub
- super.onStop();
- }
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.start_services_button:
- intent = new Intent(this,
- MyService.class);
- startService(intent);
- break;
- case R.id.stop_service_button:
- stopService(intent);
- break;
- default:
- break;
- }
- }
- }
- import android.app.Service;
- import android.content.Intent;
- import android.os.IBinder;
- import android.support.annotation.Nullable;
- import android.util.Log;
- import android.widget.Toast;
- /**
- * Created by gkumar on 4/11/2016.
- */
- public class MyService extends Service {
- private boolean isRunning = true;
- @Nullable
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onCreate() {
- Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
- Log.i("Services ::", "Service onCreate");
- isRunning = true;
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- // TODO Auto-generated method stub
- Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
- Log.d("Services::", "service started through OnStartCommand()");
- MyThread myThread = new MyThread();
- myThread.start();
- return super.onStartCommand(intent,flags,startId);
- }
- public class MyThread extends Thread {
- @Override
- public void run() {
- // TODO Auto-generated method stub
- for(int i=0; i<10; i++){
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if(isRunning){
- Log.d("Executing Services",String.valueOf(i));
- }
- }
- stopSelf(); // after completion of task it stops automatically
- }
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- Toast.makeText(MyService.this,"Service Stopped",Toast.LENGTH_SHORT).show();
- isRunning=false;
- Log.d("service :","destroyed");
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.gkumar.activityservicecomm">
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:supportsRtl="true"
- android:theme="@style/AppTheme"
- >
- <activity android:name=".MainActivity"
- android:screenOrientation="portrait">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service android:name=".MyService"/>
- </application>
- </manifest>
Step 5
Running Application

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.
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.


Summary
Read more articles on Android

Ashish TiwariPosted May 5, 2016, 12:00 AM
Very useful
Kuppurasu NagarajPosted Apr 14, 2016, 9:31 AM
Nice Sharing..
Vignesh ManiPosted Apr 14, 2016, 8:14 AM
Nice
Rahul Kumar SaxenaPosted Apr 14, 2016, 6:29 AM
Good One