Android Services
A service is a component that runs in the background to perform long-running operations without needing to interact with the user. It can continue to work even if the application is destroyed. A service is basically in one of two states -
| State | Description |
| --- | --- |
| Started | An Android application component, such as an Activity, starts a service by calling `startService()`. Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. |
| Bound | An Android application component binds to a service by calling `bindService()`. A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even perform inter-process communication (IPC). |
A service has lifecycle methods that can be used to monitor changes in its state and to perform work at the appropriate stages. The left diagram below shows the lifecycle when a service is created via `startService()`, while the right diagram shows the lifecycle when created via `bindService()`:
!(#)
To create a service, you need to create a Java class that extends the `Service` base class or one of its known subclasses. The `Service` base class defines various callback methods and most of the important methods. You do not need to implement all the callbacks. However, it is important to understand all of them to ensure your application behaves as the user expects. Implementing these callbacks ensures your app is built according to the user's expectations.
| Callback | Description |
| --- | --- |
| `onStartCommand()` | The system calls this method when another component (like an Activity) requests the service to start by calling `startService()`. If you implement this method, it is your responsibility to stop the service when its work is done, by calling `stopSelf()` or `stopService()`. |
| `onBind()` | The system calls this method when another component wants to bind to the service by calling `bindService()`. If you implement this method, you must return an `IBinder` object to provide an interface that clients can use to communicate with the service. You must implement this method if you allow binding; otherwise, return `null`. |
| `onUnbind()` | The system calls this method when all clients have disconnected from a particular interface published by the service. |
| `onRebind()` | The system calls this method when new clients connect to the service after it has already been notified that all its clients had disconnected in its `onUnbind(Intent)`. |
| `onCreate()` | The system calls this method when the service is first created via `onStartCommand()` or `onBind()`. This call is for performing one-time setup. |
| `onDestroy()` | The system calls this method when the service is no longer used or is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. |
The following main service demonstrates the lifecycle of each method -
```java
package com..androidservices;
import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;
public class HelloService extends Service {
/** Indicates how to behave if the service is killed */
int mStartMode;
/** Interface for clients that bind */
IBinder mBinder;
/** Indicates whether onRebind should be used */
boolean mAllowRebind;
/** Called when the service is being created. */
@Override
public void onCreate() {
}
/** Called every time a client starts the service using startService(). */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return mStartMode;
}
/** A client is binding to the service with bindService(). */
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** All clients have unbound with unbindService(). */
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
/** A client is binding to the service with bindService(). */
@Override
public void onRebind(Intent intent) {
}
/** Called when the service is no longer used and is being destroyed */
@Override
public void onDestroy() {
}
}
* * *
## Example
This example will walk you through the simple steps to create your own Android Service. Follow the steps to modify the Android application that was created in the Hello World example chapter:
| Step | Description |
| --- | --- |
| 1 | Use Android Studio IDE to create an Android application and name it as `androidservices` under a package `com..androidservices`. Similar to Hello World Example chapter. |
| 2 | Modify the main activity file `MainActivity.java` to add `startService()` and `stopService()` methods. |
| 3 | Create a new Java file `MyService.java` under the package `com..androidservices`. This file will have Android Service related methods. |
| 4 | Define your service in the `AndroidManifest.xml` file using the `` tag. An application can have one or more services with no restrictions. |
| 5 | Modify the default layout in the `res/layout/activity_main.xml` file to include two buttons in a linear layout. |
| 6 | Do not make any changes to constants in the `res/values/strings.xml` file. Android Studio will take care of the string values. |
| 7 | Start the Android emulator and run the application and verify the changes that you have made to the application. |
Following is the modified content of the main activity file `src/com..androidservices/MainActivity.java`. This file contains all the basic lifecycle methods. We have added `startService()` and `stopService()` methods to start and stop the service.
```java
package com..androidservices;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
// Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
// Method to stop the service
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
Following is the content of `src/com..androidservices/MyService.java` file. This file can have one or more service-related methods based on the requirement. For a beginner, we are going to implement only `onStartCommand()` and `onDestroy()` -
```java
package com..androidservices;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
Now following will be the modified content of `AndroidManifest.xml` file. Here we have added the `` tag to include our service:
```xml
Following is the content of `res/layout/activity_main.xml` file which includes two buttons:
```xml
Following is the content of `res/values/strings.xml` to define two new constants:
```xml
Android Services
MainActivity
Settings
Settings
Now let's run the modified My Application application. I assume you have created your AVD while doing environment setup. Open the activity files of your application and click on the !(#) icon from the toolbar to run the application in Android Studio. Android Studio installs the app on your AVD and starts it. If everything is fine, you will see the following Emulator window:
!(#)
Now click on the "Start Service" button to start the service. This will call the `onStartCommand()` method that we have implemented and a message "Service Started" will appear at the bottom of the emulator as follows:
!(#)
To stop the service, click the "Stop Service" button at the bottom.
YouTip