Learn Android Development For Beginners

Service

A service is a component that runs in the background to perform operations without interacting with the user. It runs at background to updating content provider, internet downloading, data processing, firing Intents, and triggering Notifications. Another Application component can start the services e.g. Activity, other service, or Broadcast Receivers etc. And it remains running even user switch to other application. You can use service where your application does not require any user action to perform actions.

Services always have higher priority than inactive or invisible activities and it is less likely that android system terminates them. The only reason Android stops a service if other foreground component requires resources. The service restarted when system resources become available again.

A service can be assigned same priority as foreground activities. It makes sure that the service will not be terminated except in extreme circumstances. E.g. in case of Music player service require to response timely to the player.

Types of Service:

A service can essentially take two forms Started and Bound. Although many tutorials generally discuss these two types of services separately, but services can work both ways. It can be started and also allows binding.

  • Started:

    A Started service run by a component (such as an activity) using method startService(). Once service is started it can run in the background indefinitely, even if the component that started it is destroyed. Usually started service does not return a result to caller and performs a single operation.

  • Bounded:

    A Bounded service bind by a component (such as an activity) using method bindService(). A component can send request and get result from service. A bound service runs only as long as other component is running that is bound to it. When all the components unbind the service, the service is destroyed.

Service Class

To create service in android applications create a subclass of Service class and override its callback method that handles the key aspects of the service. The most important callback methods of the service are

  • onStartCommand()

    The system calls this method when another component such as activity calls the startService() method to request the service started.

  • onBind()

    The system calls this method when another component want to bind with the service using bindService() method.

  • onCreate()

    The system calls this method when the service is first created, to perform one time setup procedures. The system does not call this method if service is already running. Moreover system calls this method before it calls either onStartCommand() or onBind() method.

  • onDestory()

    The system calls this method when service is no longer used and is being destroyed. Implement this method if clean up require for any resources such as threads, listeners, receivers etc.

Declaring a service in the AndroidManifest.xml

All of the services must be declared in the manifest file as we declare Activities. To declare service add the <service> element as a child of the <application> element.

 <manifest ... >
   ...
   <application ... >

 <service android:name=".MyService" />
   ...
   </application>
 </manifest>

    

Create Your First Started Service

Create a new project in Android Studio and name it “MyFirstService”. Now for creating service follow the following steps.

1. Add Service Class

Add a new class MyService and inherit it from Service class. Override the all required method of the Service class. See the sample code below.

 public class MyService extends Service {

    @Override
    public void onCreate() {

        Toast.makeText(this, "The My Service is Created", Toast.LENGTH_LONG).show();
    }

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

        Toast.makeText(this,"Service is started.", Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);

    }

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

    @Override
    public void onDestroy() {

        super.onDestroy();
        Toast.makeText(this,"Service is stopped.", Toast.LENGTH_LONG).show();

    }

 }

    

2. Add Buttons in Main Layout File

Add the two Buttons to start and stop service in the main layout file and set the Id of the buttons accordingly.

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:layout_margin="10dp"
        android:id="@+id/btnStartService" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="End Service"
        android:layout_margin="10dp"
        android:id="@+id/btnEndService" />

 </LinearLayout>

3. Write code to Start and Stop Service

In the onCreate method of the Activity class get the buttons using findViewById and register the click listener for buttons. Call startService() method on click of the start service button and stopService() method on click of the end service method.

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

     Button btnStartService = (Button)findViewById(R.id.btnStartService);
     Button btnEndService = (Button)findViewById(R.id.btnEndService);



     btnStartService.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
 
            startService(new Intent(getApplicationContext(), MyService.class));
    
        }
    });

    btnEndService.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
 
            stopService(new Intent(getApplicationContext(), MyService.class));
    
        }
    });
 
 }
    

The startService() and stopService() methods take Intent as a parameter and for Intent pass the context and service class.

4. Declare Service in Manifest.xml file

Open the manifest.xml file and add the service declaration inside the <application> tag.

 <service android:name=".MyService" />

5. Run Program

Now run the program and once the program will be load in device you will see two Buttons on the screen one for Start service and second for the Stop service.

Once application is ready. Click on the Start Service button. The application will show two messages first time in sequence “Service Created” and “Service started”. But if you press “Start Service” button again without pressing the “End Service” button the application only shows “Service started” message.

On the click of “End service” button the application shows the “Service is stopped” message.

Create Bound Service

The implementation of the Bound service is a bit similar to the Started service. But for Bound service it requires to extend class from Binder class in service and required the instance of the ServiceConnection class at the client end.

Create a new project in Android Studio or use same “MyFirstService” project for it. This example uses the same project for the Bound Service. Follow the following steps to create Bound service

1. Add Service Class

Add a new class MyBoundService and inherit it from Service class. Override the all required method of the Service class. See the sample code below.

 public class MyBoundService extends Service{

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

    IBinder binder = new LocalBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, " Service is Created", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(this, " Service bind", Toast.LENGTH_LONG).show();
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Toast.makeText(this, " Service un-bind", Toast.LENGTH_LONG).show();
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Toast.makeText(this, " Service re-bind", Toast.LENGTH_LONG).show();
        super.onRebind(intent);
    }

 }

For bound service override the onBind() and onUnbind() methods. onBind() method returns the instance of IBinder. Create the LocalBinder class and extends it from the Binder class. Override the getService() method that return the instance of service class.

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

Create a local variable binder and assign the instance of LocalBinder class to the variable. onBind() method returns this variable to client.

IBinder binder = new LocalBinder();

2. Add Buttons in Main Layout File

Add the two new Buttons to start and stop bound service in the main layout file and set the Ids as “btnStartBoundService” and “btnEndBoundService”.

3. Write code to Start and Stop Service

In the activity code file get the button using findViewById() method and register the click event for buttons.

 Button btnStartBoundService = (Button)findViewById(R.id.btnStartBoundService);
 Button btnEndBoundService = (Button)findViewById(R.id.btnEndBoundService);

 btnStartBoundService.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        bindMyService();
    }
 });

 btnEndBoundService.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        unbindMyService();
    }
 });

bindService() method take intent, connection and flag as a parameters. For connection create the instance of ServiceConnection class, and override the onServiceConnected & onServiceDisconnected callback methods.

In onServiceConnected() method we get the instance of the service in IBinder. That can be casted into the concrete class and we can directly access it. This method is called when the connection with the service has been established. It gives the service object, that can be use to interact with the service.

In onServiceDisconnected() method is called when connection with the service is unexpectedly disconnected.

    private MyBoundService myBoundService;
    private boolean isBound;

    private ServiceConnection mConnection = new ServiceConnection() {
        
        public void onServiceConnected(ComponentName className, IBinder service) {
            
            myBoundService = ((MyBoundService.LocalBinder)service).getService();

            Toast.makeText(getApplicationContext(),"Service Connected", 
Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { myBoundService = null; Toast.makeText(getApplicationContext() , "Service disconnected",
Toast.LENGTH_SHORT).show(); } }; void bindMyService() { bindService(new Intent(getApplicationContext(),MyBoundService.class), mConnection,
Context.BIND_AUTO_CREATE); isBound = true; } void unbindMyService() { if (isBound) { // Detach our existing connection. unbindService(mConnection); isBound = false; } } @Override protected void onDestroy() { super.onDestroy(); unbindMyService(); }

To bind with service call the bindService() method of the context and pass the required parameters in it. And call unbindService() method of the context to unbind from service.

4. Declare Service in Manifest.xml file

Open the manifest.xml file and add the service declaration inside the <application> tag.

 <service android:name=".MyBoundService" />

5. Run Program

Now run the program and once the program will be loaded in device it will show buttons on the screen to start and stop bound service.

On Click of Start Bound Service button, application shows three messages in sequence, “Service Created”, “Service Bind” and “Service Connected”. As we now the sequence of the method are same, the Service class first calls onCreate() method, after the creation onBind() is called and after successful binding the callback method onServiceConnected() of the connection class is called.

Click on the End Bound Service, the application shows the "Service un-bind” message.

Download Source Code

You can download the source code of the above example. (Click here to download)

;