Services in Android With Example
Services in Android With Example
Services in Android are a special component that facilitates an application to run in the
background in order to perform long-running operation tasks. The prime aim of a service is to
ensure that the application remains active in the background so that the user can operate multiple
applications at the same time. A user-interface is not desirable for android services as it is
designed to operate long-running processes without any user intervention. A service can run
continuously in the background even if the application is closed or the user switches to another
application. Further, application components can bind itself to service to carry out inter-process
communication(IPC). There is a major difference between android services and threads, one
must not be confused between the two. Thread is a feature provided by the Operating system to
allow the user to perform operations in the background. While service is an android component
that performs a long-running operation about which the user might not be aware of as it does not
have UI.
1. Foreground Services:
Services that notify the user about its ongoing operations are termed as Foreground Services.
Users can interact with the service by the notifications provided about the ongoing task. Such as
in downloading a file, the user can keep track of the progress in downloading and can also pause
and resume the process.
2. Background Services:
Background services do not require any user intervention. These services do not notify the user
about ongoing background tasks and users also cannot access them. The process like schedule
syncing of data or storing of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application like activity to bound
themselves with it. Bound services perform their task as long as any application component is
bound to it. More than one component is allowed to bind themselves with a service at a time. In
order to bind an application component with a service bindService() method is used.
In android, services have 2 possible paths to complete its life cycle namely Started and Bounded.
By following this path, a service will initiate when an application component calls the
startService() method. Once initiated, the service can run continuously in the background even if
the component is destroyed which was responsible for the start of the service. Two option are
available to stop the execution of service:
2. Bounded Service:
To carry out a downloading task in the background, the startService() method will be called.
Whereas to get information regarding the download progress and to pause or resume the process
while the application is still in the background, the service must be bounded with a component
which can perform these tasks.
A user-defined service can be created through a normal class which is extending the class
Service. Further, to carry out the operations of service on applications, there are certain callback
methods which are needed to be overridden. The following are some of the important methods of
Android Services:
Methods Description
onStartCommand() The Android service calls this method when a component(eg: activity)
requests to start a service using startService(). Once the service is started,
it can be stopped explicitly using stopService() or stopSelf() methods.
Playing music in the background is a very common example of services in android. From the
time when a user starts the service, music play continuously in the background even if the user
switches to another application. The user has to stop the service explicitly in order to pause the
music. Below is the complete step-by-step implementation of this android service using a few
callback methods.
All the strings which are used in the activity are listed in this file.
XML code:-
<resources>
<string name="app_name">Services_In_Android</string>
</resources>
Open the activity_main.xml file and add 2 Buttons in it which will start and stop the service.
Below is the code for designing a proper activity layout.
XML code:-
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#168BC34A"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp"
android:fontFamily="@font/roboto"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp"
android:textStyle="bold" />
<Button
android:id="@+id/startButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:text="@string/startButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<Button
android:id="@+id/stopButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:text="@string/stopButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
app:srcCompat="@drawable/banner" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Creating the custom service class
A custom service class will be created in the same directory where the MainActivity class resides
and this class will extend the Service class. The callback methods are used to initiate and destroy
the services. To play music, the MediaPlayer object is used. Below is the code to carry out this
task.
Java code:-
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
@Override
player.setLooping( true );
player.start();
// of the program
return START_STICKY;
@Override
super.onDestroy();
// stopping the process
player.stop();
@Nullable
@Override
return null;
}
Kotlin code:-
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.IBinder
import android.provider.Settings
player.setLooping(true)
player.start()
// of the program
return START_STICKY
super.onDestroy()
player.stop()
return null
}
Step 5: Working with the MainActivity file
Now, the button objects will be declared and the process to be performed on clicking these
buttons will be defined in the MainActivity class. Below is the code to implement this step.
Java code:-
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
@Override
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// assigning ID of startButton
start.setOnClickListener( this );
stop.setOnClickListener( this );
// process to be performed
if(view == start){
// process to be performed
Kotlin code:-
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// assigning ID of startButton
// assigning ID of stopButton
start!!.setOnClickListener(this)
stop!!.setOnClickListener(this)
// process to be performed
startService(Intent(this, NewService::class.java))
// process to be performed
stopService(Intent(this, NewService::class.java))
}
Step 6: Modify the AndroidManifest.xml file
To implement the services successfully on any android device, it is necessary to mention the
created service in the AndroidManifest.xml file. It is not possible for a service to perform its task
if it is not mentioned in this file. The service name is mentioned inside the application tag.
XML code:-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.services_in_android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
<service android:name=".NewService"/>
</application>
</manifest>