Android Services types with Examples

H Dev
6 min readJun 16, 2021

There are three types of Android system services

Let’s start with the basic question… What are android services?

All android applications use services but what is it essentially? It is an application component that runs in the background performing prolonged operations. Android services do not provide a user interface. Any application component can start an android service and when another application is opened, the former application is sent to the background and the service runs in the background unless explicitly stopped. The main purpose for this is that various applications can run simultaneously.

Components can bind themselves to a service when they seek to interact with it. They communicate via interprocess communication (IPC).

A few examples of services include playing music, handling network interactions like VoIP and such.

Services are not bound to an activities’ lifecycle.

Android processes are neither threads nor separate individual processes.

There are essentially three types of services :

  • Foreground services.
  • Background services.
  • Bound services.

Foreground Services

Operations performed by foreground service are noticeable by the user. Foreground services are displayed in notifications. Even when the app is not the one on the screen that the user is interacting with, it continues its execution. For most such services, the notification must always be visible until the service is stopped or removed by the user.

  • Example : Music player.

Here, for better understanding of the concept let’s assume a song playing on a music provider — Spotify.

Reference from device (OnePlus 6.) — Music playing on spotify and music playing in background when on Google Docs app.

When we choose a song to play and play it, it begins to play. Meanwhile we can browse through the same app, we can switch through various pages and browse through countless number of other songs, as long as we do not change the current playing song, it continues to play. And even if we switch to another application, it still continues to play. And now the music player creates a notification and the user can view the service that is running. This is an example of a foreground process that is running.

Above attached are a few images illustrating the scenario of working of foreground services.

The user is actively aware of a foreground service that is running. Foreground services cannot be explicitly killed when the system is low on memory. Also note that these notifications cannot be dismissed like other notifications. That is because these are placed on the notifications panel as ‘ongoing heading’ and thus cannot be swiped to dismiss.

public class NotificationService extends Service {

private static final int SERVICE_ID = 101;

@Nullable @Override public IBinder onBind(Intent intent) {

return null;

}

@Override public void onCreate() {

super.onCreate();

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

String channelId = createNotificationChannel(notificationManager);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);

Notification notification =

notificationBuilder.setOngoing(true)

.setContentTitle(“Navigine Service Example”)

.setCategory(NotificationCompat.CATEGORY_SERVICE)

.build();

startForeground(ID_SERVICE, notification);

}

@Override public int onStartCommand(Intent intent, int flags, int startId) {

super.onStartCommand(intent, flags, startId);

return START_REDELIVER_INTENT;

}

private String createNotificationChannel(NotificationManager notificationManager){

String channelId = “NAVIGINE_SERVICE_CHANNEL_ID_EXAMPLE”;

String channelName = “NAVIGINE CHANNEL NAME EXAMPLE”;

NotificationChannel channel = new NotificationChannel(channelId,

channelName,

NotificationManager.IMPORTANCE_HIGH);

channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); // will be shown in lock screen

notificationManager.createNotificationChannel(channel);

return channelId;

}

}

Code for a foreground service . (13)

NotificationService is a user defined class that extends the Service class. , used for creating services.

The OnCreate() method is invoked once and is used to setup the whole service when it is initialized/called

The OnStratCommand() method starts the notification, when not mentioned the service is automatically killed after a minute of its execution.

Notification is a mandatory part of creating a foreground service. Without notification a foreground service cannot be created. The running state is determined by the parameters returned to the OnStratCommand().

OnBind() method is invoke when the service wants to bind with another component. This is implemented with the aid of an IBinder.

OnDestroy() method is invoked when the service is stopped and destroyed. This is the last call in the service lifecycle. It cleans up after any resources that are allocated to the service, such as threads, processes, or any active listeners.

Background Services

Background services according to android developers documentations states that, A background service performs an operation that isn’t directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service. [5] We have our bluetooth service, when turned on, it constantly searches for devices to pair with in the background. These services do not intervene with the user’s usage. These services include other processes such as logging, system monitoring, scheduling, and user notification.

Background Service is a component which runs in the background, with no direct interaction with the user. That is the service does not have an user Interface. As the service has no user interface it is not bound to the lifecycle of any particular activity. These services are used for repetitive and potential long running operations, checking for new data, data processing, indexing content, etc. Android set up restrictions recently on various background services and because of these recent restrictions on Android to improve battery life, all background work including periodic tasks should now be scheduled through the JobScheduler.

  • Example : Alarm Service.

Alarm is an example for a background service that runs continuously irrespective of the foreground service. It does not necessarily have a UI but it runs in the background. And when the time is set right, the alarm rings. This service is provided by the background process. Upon the time the process is automatically invoked.

public class NavigineBroadcastReceiverExample extends BroadcastReceiver {

// here you need to receive some action from intent and depending on this action start service or set repeating alarm

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

try{

if (action.equals(“START”)) {

Intent wakeIntent = new Intent(“WAKE”);

wakeIntent.setClass(context, YourReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(

context, 0,

wakeIntent,

PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmService = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

if (alarmService != null)

alarmService.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 15 * 60 * 1000, pendingIntent);

} else if (action.equals(“WAKE”)) {

JobScheduler jobShedulerService = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

jobShedulerService.schedule(new JobInfo.Builder(1, new ComponentName(context, YourJobClass.class))

.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)

.setMinimumLatency(0L)

.setOverrideDeadline(15 * 60 * 1000)

.build());

Intent wakeIntent = new Intent(“WAKE”);

wakeIntent.setClass(context, YourReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(

context, 0,

wakeIntent,

PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmService = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

if (alarmService != null)

alarmService.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + Default.NAVIGINE_JOB_SERVICE_WAKEUP_TIME * 1000, pendingIntent);

}

} catch (Throwable e) {

Logger.d(TAG, 1, Log.getStackTraceString(e));

}

}

}

Other background services include services such as launchers.

Bound Services

A few certain services bind themselves to a particular task. They can be put into the background or can work as foreground services as well, but what is varied is that fact that they are binded with an activity.

  • Example : Navigation Home to Destination. Bound services need not work in foreground as well. They are linked to a service, like in this case lthey are linked to the GPS service.

References :

  1. System Service In AOSP. A Service is an application component… | by Budhdi Sharma | AndroidPub
  2. Android Service Tutorial — javatpoint
  3. Services in Android with Example
  4. Foreground services
  5. Services overview
  6. Foreground Services in Android. In this tutorial, I’ll talk about the… | by Jeet Dholakia
  7. Foreground Service
  8. Foreground Service
  9. Foreground Service Android Example — AndroidWave
  10. Effective foreground services on Android
  11. What is the difference between a background and foreground service?
  12. Android Foreground Service Restrictions | by Elvina Sh
  13. https://gist.githubusercontent.com/MrCrambo/82bfb3f11b918882ab1425371edce6eb/raw/4a0cc41f48b4e8238436d5b85633032150ef9fcd/foreground_service.java
  14. android.app.Service
  15. Starting Background Services
  16. Bound Services in Xamarin.Android — Xamarin
  17. Bound Service Tutorial by Using Messenger — androidtutorialmagic
  18. Service not being created (or connecting) after bindService()
  19. Securing Services
  20. Starting Background Services
  21. Background Location Limits
  22. Android Bound Services. Bound Services is a great way to… | by Anant
  23. Bounded Service Android With Example | AndroidMonks
  24. Bound Services | Android Developers

--

--

H Dev

just another X-shaped personality, love to learn and tinker with new tech.