What is a Service in Android?
A Service in Android is a component that runs in the background without a user interface. It is useful for long-running tasks such as:
✅ Playing music
✅ Downloading files
✅ Fetching data from the internet
✅ Running a background task (e.g., location tracking)
Types of Services in Android
Service Type | Description | Example |
Started Service | Runs in the background until stopped manually | Music Player, File Download |
Bound Service | Allows communication between an Activity and the Service | Fetching Data from API |
Foreground Service | Runs with higher priority and shows a notification | GPS Tracking, Music Player |
Example: Creating a Service in Android
We will create an app where:
✅ A Service runs in the background
✅ The Activity binds to the Service and retrieves data
✅ The Service runs in a separate thread
Add Service in AndroidManifest.xml
<service android:name=".MyService" />
Create a Service (MyService.java)
public class MyService extends Service {
private final IBinder binder = new MyBinder();
private int counter = 0;
private boolean isRunning = true;
public class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
public IBinder onBind(Intent intent) {
return binder;
}
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(() -> {
while (isRunning) {
counter++;
Log.d("MyService", "Counter: " + counter);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
return START_STICKY;
}
public int getCounter() {
return counter;
}
public void onDestroy() {
super.onDestroy(); // Ensure you call the superclass method
isRunning = false;
Log.d("MyService", "Service is stopped.");
}
}
✅ This Service runs in the background
✅ It increments a counter every second
✅ It runs in a separate thread using new Thread(() -> {...}).start();
XML Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service" />
<Button
android:id="@+id/btnBind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bind to Service" />
<TextView
android:id="@+id/textViewCounter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:paddingTop="20dp"/>
</LinearLayout>
✅ Button 1 → Starts the Service
✅ Button 2 → Binds to the Service and gets the counter value
✅ TextView → Displays the counter value
Java Code (MainActivity.java)
public class MainActivity extends AppCompatActivity {
private MyService myService;
private boolean isBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = findViewById(R.id.btnStart);
Button btnBind = findViewById(R.id.btnBind);
TextView textViewCounter = findViewById(R.id.textViewCounter);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
});
btnBind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isBound) {
int count = myService.getCounter();
textViewCounter.setText("Counter: " + count);
}
}
});
}
// Service connection to bind the activity with the service
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder binder = (MyService.MyBinder) service;
myService = binder.getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
}
};
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (isBound) {
unbindService(serviceConnection);
isBound = false;
}
}
}
✅ Click “Start Service” → Starts the service in the background
✅ Click “Bind to Service” → Fetches the counter value from the service