Android Services is the main component in android application development, its provide facilities to perfume long-running operation. By default Android services run on Main Thread (UI thread), for a run in the background you have to make it.
No UI is provided in Android Services. Services can start from another component and run in the device even switching an application. Like downloading an app or play music.
Android Services Types
1. Foreground
Foreground services are noticeable to the user and can see what happening or interact with the component. For example a Music player and Downloading file applications works. Foreground services continue running even users are not interacting or using them.
2. Background
Background service runs in the background without the user knows or the user can’t see it. For example, Storing data and Sync data to the server. Some tasks do not need to show users what is happing in the background of the app.
Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn’t in the foreground. In most cases like this, your app should use a scheduled job instead.
“Official Android”
3. Bound
Bound service runs only as long as another application component bound to it. Multiple components can bind to the service at once, but if all of them unbind, the service will destroy. By calling,bindService()
service is bind with the application component.
Caution: Android Services is running in MainThread, So If your service is going to perform any blocking operation like Music play or downloading (networking work), you should create a new thread within the service. By separate thread, you can prevent ANR ( Application Not Responding ) error and crash.
Let’s build a Simple Android Service Example app :
In this example, we will build a very simple android service example. to see how you can stop and start service in android app.
Step 1. Create a new project “Build Your First Android App in Kotlin“
Step 2. Now create a class “MyService.java” and extend “Service” class
Implement must methods IBinder and override a onStartCommand(...)
– > to start service,onDestroy()
-> to stop service. You can think about it how to use in your apps.
Add the following code in “MyService.java“
package in.eyehunt.androidservices; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.widget.Toast; public class MyService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } }
Step 3. Define service in AndroidManifest.xml file.
Here we have added <service.../>
tag to include our service −
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="in.eyehunt.androidservices"> <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> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyService"/> </application> </manifest>
Step 4. Add two button in a main_activity.xml resource layout file
This button is for Start and Stop service in the app.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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="in.eyehunt.androidservices.MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="tutorial.eyehunts.com" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="16dp" android:text="Start" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <Button android:id="@+id/button_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="16dp" android:text="stop" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button_start" /> </android.support.constraint.ConstraintLayout>
Step 5. Add the following code in MainActivity.java
In MainActivity we are passing intent to startService(...)
-> start service and stopService(...)
-> stop service
package in.eyehunt.androidservices; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //On start button click start service Button start = (Button) findViewById(R.id.button_start); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startService(new Intent(getBaseContext(), MyService.class)); } }); //On stop button click start service Button stop = (Button) findViewById(R.id.button_stop); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopService(new Intent(getBaseContext(), MyService.class)); } }); } }
Step 6. Run the application, in an emulator or On your Android device
Output screenshot Android service example :
Download source code Android Service example :
https://github.com/EyeHunts/AndroidServices
Note : This example (Project) is developed in Android Studio 3.0.1 . Tested on Android 9 ( Android P), compile SDK version API 26: Android 8.0 (Oreo)
MinSdkVersion=”15″
TargetSdkVersion=”26″
Coding in Java
Android Services callback methods & Description :
onStartCommand()
This method invoked when calling the startService()
. Another component of the app can start this service like start from Activity. If you implement this, then you have to stop the service, when its work was completed by calling stopSelf()
or stopService()
.
onBind()
When another component wants to bind with service. In your app must implement this method and provide an interface to the client can communicate with the service by returning an IBinder.
You must always implement this method; however, if you don’t want to allow binding, you should return null.
onUnbind()
The system calls this method when all clients have disconnected from a particular interface published by the service.
onCreate()
This method performs one-time setup procedures when the service is initially created. But its calls either onStartCommand() or onBind() methods before onCreate(). Note, If the service already running then the onCreate() method is not called.
onDestroy()
This method is invoked, when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, or receivers. The onDestroy() is the last call method, that the service receives.
Android Service Lifecycle :
Below diagram from the google android site to show how Service lifecycle callback methods are invoked. You can implement this method to monitor changes in the service’s state and perform the action at the time.
Note: You are not required to call the superclass implementation of these all callback methods. Unlike the activity lifecycle callback methods invoked. The onCreate()
and onDestroy()
methods are called for all services, whether they’re created by startService()
or bindService()
.