Services in Android

Deepak Kaligotla
4 min readSep 2, 2023

--

Services

Android Services can be classified into three types based on how they run and interact with the rest of the system:

  1. Foreground Service: A foreground service is a service that has a notification attached to it, which shows up in the notification tray. This type of service is typically used for tasks that require ongoing user interaction or attention, such as music playback, navigation, or a running timer. Foreground services are given higher priority than background services and are less likely to be killed by the system to free up resources. An example of a foreground service is a music player service that keeps playing music and shows a notification with playback controls.
      public class MyForegroundService extends Service {
private static final String CHANNEL_ID = "MyForegroundServiceChannel";

@Override
public void onCreate() {
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Create notification for the foreground service
createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service Example")
.setContentText("This is an example of a foreground service in Android.")
.setSmallIcon(R.drawable.ic_notification)
.build();

// Start the foreground service
startForeground(1, notification);

// Do some work here
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT);

NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
}

2. Background Service: A background service is a service that runs in the background and does not have a user interface. This type of service is typically used for tasks that do not require user interaction or attention, such as syncing data, fetching updates, or monitoring sensors. Background services are less likely to be killed by the system than the foreground services, but they may be killed if the system runs low on resources. An example of a background service is a location service that continuously tracks the user’s location in the background.

      public class MyBackgroundService extends Service {
private Handler mHandler;
private Runnable mRunnable;
private int mInterval = 10000; // 10 seconds by default

@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
mRunnable = new Runnable() {

@Override
public void run() {
// Do something in the background
Log.d("MyBackgroundService", "Service is running");
mHandler.postDelayed(this, mInterval);
}
};
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandler.post(mRunnable);
return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(mRunnable);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

3. Bound Service: A bound service is a service that allows other components (such as activities or other services) to bind to it and communicate with it through an interface. This type of service is typically used for tasks that require interaction with other components, such as sharing data, performing calculations, or handling requests. Bound services are destroyed when there are no more components bound to them, which makes them more resource-efficient. An example of a bound service is a music player service that exposes an interface for controlling the playback and retrieving the current track information.

Note that in order to use a bound service, you need to declare it in the manifest file: <service android:name=“.BoundserviceClassName”/>

      public class MyBoundService extends Service {

private IBinder binder = new MyBinder();

public class MyBinder extends Binder {
MyBoundService getService() {
return MyBoundService.this;
}
}

@Override
public IBinder onBind(Intent intent) {
return binder;
}

public int getRandomNumber() {
return new Random().nextInt(100);
}
}

public class MainActivity extends AppCompatActivity {

private MyBoundService myService;
private boolean isBound = false;

private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyBoundService.MyBinder binder = (MyBoundService.MyBinder) service;
myService = binder.getService();
isBound = true;
}

@Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onDestroy() {
super.onDestroy();
if (isBound) {
unbindService(connection);
isBound = false;
}
}

public void onClickGetRandomNumber(View view) {
if (isBound) {
int randomNumber = myService.getRandomNumber();
Toast.makeText(this, "Random number: " + randomNumber, Toast.LENGTH_SHORT).show();
}
}
}

In summary, the different types of Android Services are designed to handle different types of tasks and use cases. Developers can choose the appropriate type of service based on their app’s requirements and performance considerations.

--

--

Deepak Kaligotla

I’m jobless, have 5.5 yrs experience in IT Tech support/helpdesk. Love learning and developing Mobile applications (Android & iOs). Contact me if you can hire