Android Development

Google's android guide Home Contact

Android Services

Android service class can be used to run a task without any UI. It can be short term tasks or long term. They can run with or without user interaction and long term service tasks can run in the background even when the application is closed. Examples of Service include running in background various tasks such as playing music after calling from another application, doing some task over the network while user is watching news, loading an Image or a file, or download something from the Internet asynchronously.

Android Service States

  • Not Started: The service is not yet started. In this state it haven't called startService() or bindService() to initiate it.
  • Started: The service is running in response to a startService() call. The service's onCreate() and onStartCommand() methods are called, and it runs in the background. User can use a started service for tasks.
  • Bound:The service is bound to one or more clients using bindService(). The service can communicate with the client components (usually activities or fragments) that have bound to it.
  • Stopped: The service has been stopped or unbound by calling stopService() or unbindService().
  • Destroyed:The service is terminated and its resources are released. The onDestroy() method is called.

Service Lifecycle Methods

  • onCreate(): This method is called when the service is first created, typically during the startService() or bindService() call. Perform one-time initialization tasks here.
  • onStartCommand(): If the service is started using startService(), this method is called. It receives an Intent which can pass data and instructions to the service. It can also return a value that specifies how the service should behave when it's killed or restarted by the system.
  • onBind(): If the service is bound using bindService(), this method is called to create a connection between the service and the client. It returns an IBinder interface that the client can use to interact with the service.
  • onUnbind(): Called when all clients have disconnected from a bound service. Perform cleanup tasks here.
  • onDestroy(): Called when the service is no longer needed and is about to be destroyed. Release any resources and clean up service here.

Services can be categorized as one of the following types:

Foregound Services

This kind of services run in foreground during user interactions. User can pause and resume the service while task is performed, such as downloading file from internet, playing music or tracking user location etc. They must display notification to users that service is running. Foreground services have higher priority then background services, and less liley to be killed by the system to free up resources.

Sample code for a foreground service that plays music in the background.

    
    public class MusicService extends Service {

    private MediaPlayer mediaPlayer;
    private boolean isPlaying;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Initialize the media player and start playing music
        mediaPlayer = MediaPlayer.create(this, R.raw.song);
        mediaPlayer.setLooping(true);
        mediaPlayer.start();

        // Create a notification to display while the service is running
        Notification notification = new NotificationCompat.Builder(this, "MusicChannel")
                .setContentTitle("Music Player")
                .setContentText("Playing music")
                .setSmallIcon(R.drawable.ic_music)
                .build();

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

        isPlaying = true;

        return START_NOT_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the media player when the service is stopped
        mediaPlayer.stop();
        isPlaying = false;
    }

// returns null as we don't need to bind this service
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}


Background Services

This kind of services can run in background without any user interaction. These services do not notify the user about ongoing background tasks and users also cannot access them. They are used to perform tasks that need to run continuously in the background even when application started them is not in forefround. Examples of such service include checking for updates, uploading or downloading data, or monitoring the device's sensors etc. They can be killed by the system if running low on memory or resources, so they need to be design these services carefully for optimal use of resources. There are different types of background services in Android, such as started services and bound services. Started services are services, which are started by an application and run in the background until they complete their task or are stopped by the system or the application that started them. Bound services are services that are bound to an application and allow the application to communicate with the service and exchange data.

Example of a service that runs in the background:

    
    
    public class BackgroundService extends Service {

    private boolean isRunning;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("BackgroundService", "Service started");

        // Perform a task in the background
        new Thread(new Runnable() {
            @Override
            public void run() {
                // Do some background work here
                // ...

                // Stop the service when the task is complete
                stopSelf();
            }
        }).start();

        // Return START_STICKY to indicate that the service should be restarted if it is killed by the system
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
        Log.d("BackgroundService", "Service stopped");
    }

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

Bound Services

This type of service allows more than one application component to bind to it, while it runs, such as an activity binded to the running service,with which it can communicate with and get results from it.