Introduction
A Service in Android can be consider as an application component that can use for perform long-running operations in the background. Service does not have a user interface. Once you started service, it might continue running for some time even after the user switches to another application. For example, a service can do network transactions, play music, perform file I/O, and interact with a content provider, from the background.
Types of Services
We have three different types of services in Android:-
Foreground
A foreground service use to perform some operation that is noticeable to the user. For example, a music app would use a foreground service to play a music track. Foreground services must have a Notification that is visible to user. Foreground services continuously run in background even when the user isn’t interacting with the app.
While working with Foreground service, you have to display a notification so that users are actively notice that the service is running. Keep in mind that this notification cannot be dismissed until service is either stopped or removed from the foreground.
Background
A background service use to perform an operation that isn’t directly visible to the user. For example, if an app used a service to compact its storage, that service would be a background service.
Bound
A service is said to be bound when an application component binds to it by the use of bindService(). A bound service offers a client-server interface that helps to the components to interact with the service, send requests, receive results etc. A bound service is run when another application component is bound to it. Keep remember that Multiple components can bind to the service at once, but when all of them unbind it, the service is destroyed.
What to choose a service or a thread
Here some developer confuse mostly who just start development what to choose for background work a service or thread and also this question is mostly asked by interview.
Choosing between service and thread is quit simple if you want to perform some background work without the interacting with the user then you should go for service because a service is a android component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need. And if you want to perform work that is outside of your main thread, but you want user must interacting with your application, you should go with thread For example, if you want to play some audio, but only while user interacting with it or your activity is running, you just need to create a thread in onCreate(), start running it in onStart(), and stop it in onStop().
Keep remember that if you are using a service, it continuously run in your application’s main thread by default, so for this you should still create a new thread within the service if it performs kind of intensive or blocking operations.
fundamentals of Android Services
Android service provide certain callback methods which we need to be overridden if we going to use service. Here is the following are some of the important methods of Android Services:
onStartCommand()
Android service calls this method when a view(eg: activity) wants to start a service by the use of startService(). Keep in mind once the service is started, it can be stopped explicitly by the use of stopService() or stopSelf() methods
onBind()
This method is compulsory to implement when you are using android service and must be invoked whenever any application component calls the bindService() method to bind itself with a service. For this User-interface is need to communicate with the service effectively by returning an IBinder object. Keep remember If the binding of service is not required then the method must return null.
onUnbind()
The Android service use this method when all the clients/user get disconnected from a particular service interface.
onRebind()
This method is used when all clients are disconnected from the particular service and there is a need again to connect the service with new clients
onCreate()
This method is necessary to perform a one-time-set-up. Whenever a service is created either using onStartCommand() or onBind(),the android system calls this method.
onDestroy()
This method is use when a service you are using is no longer in use. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.
Life Cycle of Android Service
Service has two forms that’s why service life cycle can follow two different paths: started or bound.
- Started
- Bound
1) Started Service
Started service are those which is start by component like activity and it run in the background indefinitely.This type of service is stop by stopService() method and it also stop it self by calling the stopeSelf() method.
2) Bound Service
A service is said to be bound when any another component (e.g. client) calls bindService() method. This type of service is unbind by calling the unbindService() method.
This service cannot be stopped until all of the clients unbind the service.
Let’s see an example
1:-AndroidManifest.xml
The most important part is to mention service in manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codinglance.service">
<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/Theme.Service">
<activity android:name=".SecondScreen"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ServiceClass"
android:enabled="true" />
</application>
</manifest>
2:-MainActivity
In this file we have 3 buttons which is used for start service, stope service and to go next screen.
class MainActivity : AppCompatActivity() ,View.OnClickListener{
var startServiceBtn: Button? = null
var stopServiceBtn:Button? = null
var nextServiceBtn:Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startServiceBtn = findViewById(R.id.startServiceBtn);
stopServiceBtn = findViewById(R.id.stopServiceBtn);
nextServiceBtn = findViewById(R.id.nextServiceBtn);
startServiceBtn!!.setOnClickListener(this);
stopServiceBtn!!.setOnClickListener(this);
nextServiceBtn!!.setOnClickListener(this);
}
override fun onClick(src: View) {
when (src.id) {
R.id.startServiceBtn -> startService(Intent(this, ServiceClass::class.java))
R.id.stopServiceBtn -> stopService(Intent(this, ServiceClass::class.java))
R.id.nextServiceBtn -> {
val intent = Intent(this, SecondScreen::class.java)
startActivity(intent)
}
}
}
}
3:-Activity_main.xml
Layout file of MainActivity which have 3 buttons.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
>
<Button
android:id="@+id/startServiceBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Start Service" />
<Button
android:id="@+id/stopServiceBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Stop Service" />
<Button
android:id="@+id/nextServiceBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Next Page" />
</RelativeLayout>
4:-SecondScreen
This is the second screen
class SecondScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second_screen)
}
}
5:-activity_second_screen
Layout file of SecondScreen.
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".SecondScreen">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="200dp"
android:text="Second Screen"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
6:-ServiceClass
This is the service class which extend Service and override it’s methods.for music file you can download any music file and paste into raw folder.
open class ServiceClass : Service() {
var myPlayer: MediaPlayer? = null
@Nullable
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show()
myPlayer = MediaPlayer.create(this, R.raw.sun)
// Here we Set looping
myPlayer!!.isLooping = false
}
override fun onStart(intent: Intent?, startid: Int) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show()
//here music player will start
myPlayer!!.start()
}
override fun onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show()
//here music player will stop
myPlayer!!.stop()
}
}