Intent Service in Android with Example
Last Updated :
06 Feb, 2023
An IntentService is a subclass of Service in Android that is used to handle asynchronous requests (expressed as “Intents”) on demand. It runs in the background and stops itself once it has processed all the intents that were sent to it.
An IntentService in Java and Kotlin:
Kotlin
class MyIntentService : IntentService( "MyIntentService" ) {
override fun onHandleIntent(intent: Intent?) {
}
}
|
Java
public class MyIntentService extends IntentService {
public MyIntentService() {
super ( "MyIntentService" );
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
|
You can start an IntentService by creating an Intent object and passing it to the startService() method. The Intent should contain any data that you want to pass to the service.
Kotlin
val intent = Intent( this , MyIntentService:: class .java)
intent.putExtra( "data" , "my data" )
startService(intent)
|
Java
Intent intent = new Intent( this , MyIntentService. class );
intent.putExtra( "data" , "my data" );
startService(intent);
|
IntentService runs on a single background thread, so if you have multiple requests, they will be queued and processed one after the other, it could also stop itself after processing all intents. For better performance and to avoid ANR (Application not responding), you should offload long-running or heavy tasks to a separate thread within the onHandleIntent() method. An IntentService is a good choice when you have a small number of tasks that need to be done in the background, and you don’t need to run them concurrently.
Step-by-Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Declaring IntentService in the AndroidManifest.xml File
Go to the AndroidManifest.xml file and declare this service within the <application> element.
<service
android:name=".ExampleIntentService"
android:exported="false" />
Step 3: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:gravity = "center"
android:orientation = "vertical" >
< Button
android:id = "@+id/start_service_button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Start Service" />
</ LinearLayout >
|
Create a new class called ExampleIntentService that extends IntentService. Below is the code for the activity_example_intent_service.xml file. Comments are added inside the code to understand the code in more detail.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< androidx.constraintlayout.widget.ConstraintLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".ExampleIntentService" >
< TextView
android:id = "@+id/textView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Second Activity"
android:textSize = "32dp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</ androidx.constraintlayout.widget.ConstraintLayout >
|
Step 4: Working with the MainActivity & ExampleIntentService File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val startServiceButton = findViewById<Button>(R.id.start_service_button)
startServiceButton.setOnClickListener {
val intent = Intent( this @MainActivity , ExampleIntentService:: class .java)
startService(intent)
}
}
}
|
Java
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startServiceButton = findViewById(R.id.start_service_button);
startServiceButton.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity. this , ExampleIntentService. class );
startService(intent);
});
}
}
|
Override the onHandleIntent() method to specify the task that you want to perform in the background. Below is the code for the ExampleIntentService File. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.app.IntentService
import android.content.Intent
import android.util.Log
class ExampleIntentService : IntentService( "ExampleIntentService" ) {
constructor(): super ( "ExampleIntentService" )
override fun onHandleIntent(intent: Intent?) {
Log.d( "ExampleIntentService" , "Task in progress" )
try {
Thread.sleep( 5000 )
} catch (e: InterruptedException) {
e.printStackTrace()
}
Log.d( "ExampleIntentService" , "Task completed" )
}
}
|
Java
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.Nullable;
public class ExampleIntentService extends IntentService {
public ExampleIntentService() {
super ( "ExampleIntentService" );
}
@Override
protected void onHandleIntent( @Nullable Intent intent) {
Log.d( "ExampleIntentService" , "Task in progress" );
try {
Thread.sleep( 5000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d( "ExampleIntentService" , "Task completed" );
}
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...