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:
class MyIntentService : IntentService( "MyIntentService" ) {
override fun onHandleIntent(intent: Intent?) {
// Perform some background task here
}
} |
public class MyIntentService extends IntentService {
public MyIntentService() {
super ( "MyIntentService" );
}
@Override
protected void onHandleIntent(Intent intent) {
// Perform some background task here
}
} |
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.
val intent = Intent( this , MyIntentService:: class .java)
intent.putExtra( "data" , "my data" )
startService(intent) |
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 version = "1.0" encoding = "utf-8" ?>
< LinearLayout android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:gravity = "center"
android:orientation = "vertical" >
<!-- Button to start the service -->
< 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 version = "1.0" encoding = "utf-8" ?>
< androidx.constraintlayout.widget.ConstraintLayout android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".ExampleIntentService" >
<!-- TextView to display the title of the activity -->
< 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.
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)
// Get a reference to the start service button in the layout
val startServiceButton = findViewById<Button>(R.id.start_service_button)
// Set an OnClickListener for the button
startServiceButton.setOnClickListener {
// Create an Intent to start
// the ExampleIntentService
val intent = Intent( this @MainActivity , ExampleIntentService:: class .java)
// Start the service
// using the intent
startService(intent)
}
}
} |
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);
// Get a reference to the start service button in the layout
Button startServiceButton = findViewById(R.id.start_service_button);
// Set an OnClickListener for the button
startServiceButton.setOnClickListener(v -> {
// Create an Intent to start
// the ExampleIntentService
Intent intent = new Intent(MainActivity. this , ExampleIntentService. class );
// Start the service
// using the intent
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.
import android.app.IntentService
import android.content.Intent
import android.util.Log
class ExampleIntentService : IntentService( "ExampleIntentService" ) {
// Constructor with a name for the worker thread
// The name is used only for debugging purposes.
constructor(): super ( "ExampleIntentService" )
// This method is called on a worker thread
// with a request to process.
override fun onHandleIntent(intent: Intent?) {
// Perform a task in the background
Log.d( "ExampleIntentService" , "Task in progress" )
try {
// Perform the task for 5 seconds
Thread.sleep( 5000 )
} catch (e: InterruptedException) {
// Print the stack trace
// if an interruption occurs
e.printStackTrace()
}
Log.d( "ExampleIntentService" , "Task completed" )
}
} |
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.Nullable;
public class ExampleIntentService extends IntentService {
// Constructor
public ExampleIntentService() {
// Call superclass constructor with
// the name of the worker thread
super ( "ExampleIntentService" );
}
@Override
protected void onHandleIntent( @Nullable Intent intent) {
// Perform a task in the background
Log.d( "ExampleIntentService" , "Task in progress" );
// Simulate a long running task by
// sleeping the thread for 5 seconds
try {
Thread.sleep( 5000 );
} catch (InterruptedException e) {
// Print stack trace if an
// InterruptedException occurs
e.printStackTrace();
}
Log.d( "ExampleIntentService" , "Task completed" );
}
} |