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,
- <?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>
Step 2
Add the following code to the MainActivity.java,
- 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() {
-
-
-
- super.onStart();
- }
-
- @Override
- protected void onStop() {
-
-
- 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;
- }
-
- }
-
- }
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,
- 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;
-
-
-
-
- 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) {
-
- 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() {
-
- for(int i=0; i<10; i++){
- try {
- Thread.sleep(3000);
-
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
- if(isRunning){
- Log.d("Executing Services",String.valueOf(i));
- }
- }
- stopSelf();
- }
-
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- Toast.makeText(MyService.this,"Service Stopped",Toast.LENGTH_SHORT).show();
- isRunning=false;
- Log.d("service :","destroyed");
- }
- }
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.
- <?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 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