Android Background Service Tutorial – How to work Background Service in android Example

By | April 18, 2019
Background Service in Android Tutorial Example

What is Services/Background Service ?

Services is an application component that can perform background operation.it can not provide user interface.Another Application component can start a service and its continue to run in the background event if user switches to another application.

Services component is used to perform operations on the background.Like Playing Music,Internet download process.Services is bounded by component to perform interactive or inter process communications.

Life Cycle Of Services

Started Service : A Service is started when component (Ex : activity) called startService() Method used.Now in this method to call and run the background services.When service is stopped to call stopService() Method Used.Service Can be stopped itself to use stopSelf() Method.

Bound Service : A Service is bound when Application component to used bindService() Method call.And Service is unbind to used unBindService() Method used.

Now Service Life cycle Flow Given Below :

Above Image Flow to Different Different Service Life Cycle First one is startService and Second Flow is bindService.

Methods of Services

onCreate() : In this method to used when the service is first time created to using this method.if the service is already running this method is does not called.

onStartCommand() : In this method to used when another activity component request to the service will be started to call this method.when this method is call to service is started and run the background.if this is implement it is your responsibility to stop the service when its work to called method is stopService() or stopSelf().

onBind() : onBind() Method is used to bind the services and its used to bindService() method.if this method is implement to you must be provide interface that can clients are communicate to service and its returning is IBinder object.

onRebind() : onRebind() Method is when the client is already connected to the service after it had previously all the disconnected to  in its onUnbind() to use this method.

onUnbind() : onUnbind() Method is used of when all clients has disconnected from particular interface published by service.

onDestroy() : In This method when the service is no longer used and its destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.

Implementation of Services

First You can Create activity_main.xml File

Now Create MainActivity.java File

Now Another Create MyService.java Class

Important You need to register service class in AndroidManifest.xml File write Code in AndroidManifest.xml file following this :

Now In this Example of Two button create and start and stop service used method when user to click button and called this methods. and start service in run background to display toast message.