Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

60. Android Local Bound Services – A Worked Example

As outlined in some detail in the previous chapters, bound services, unlike started services, provide a mechanism for implementing communication between an Android service and one or more client components. The objective of this chapter is to build on the overview of bound services provided in “An Overview of Android Started and Bound Services” before embarking on an example implementation of a local bound service in action.

60.1 Understanding Bound Services

In common with started services, bound services are provided to allow applications to perform tasks in the background. Unlike started services, however, multiple client components may bind to a bound service and, once bound, interact with that service using a variety of different mechanisms.

Bound services are created as sub-classes of the Android Service class and must, at a minimum, implement the onBind() method. Client components bind to a service via a call to the bindService() method. The first bind request to a bound service will result in a call to that service’s onBind() method (subsequent bind requests do not trigger an onBind() call). Clients wishing to bind to a service must also implement a ServiceConnection subclass containing onServiceConnected() and onServiceDisconnected() methods which will be called once the client-server connection has been established or disconnected, respectively. In the case of the onServiceConnected...

60.2 Bound Service Interaction Options

There are two recommended mechanisms for implementing interaction between client components and a bound service. In the event that the bound service is local and private to the same application as the client component (in other words it runs within the same process and is not available to components in other applications), the recommended method is to create a subclass of the Binder class and extend it to provide an interface to the service. An instance of this Binder object is then returned by the onBind() method and subsequently used by the client component to directly access methods and data held within the service.

In situations where the bound service is not local to the application (in other words, it is running in a different process from the client component), interaction is best achieved using a Messenger/Handler implementation.

In the remainder of this chapter, an example will be created with the aim of demonstrating the steps...

60.3 An Android Studio Local Bound Service Example

The example application created in the remainder of this chapter will consist of a single activity and a bound service. The purpose of the bound service is to obtain the current time from the system and return that information to the activity where it will be displayed to the user. The bound service will be local and private to the same application as the activity.

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter LocalBound into the Name field and specify com.ebookfrenzy.localbound as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

Once the project has been created, the next step is to add a new class to act as the bound service.

60.4 Adding a Bound Service to the Project

To add a new class to the project, right-click on the package name (located under app -> java -> com.ebookfrenzy.localbound) within the Project tool window and select the New -> Service -> Service menu option. Specify BoundService as the class name and make sure that both the Exported and Enabled options are selected before clicking on Finish to create the class. Android Studio will load the BoundService.java file into the editor where it will read as follows:

package com.ebookfrenzy.localbound;

 

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

 

public class BoundService extends Service {

    public BoundService() {

    }

 

    @Override

    public IBinder onBind(Intent intent) {

        // TODO: Return the communication...

60.5 Implementing the Binder

As previously outlined, local bound services can communicate with bound clients by passing an appropriately configured Binder object to the client. This is achieved by creating a Binder subclass within the bound service class and extending it by adding one or more new methods that can be called by the client. In most cases, this simply involves implementing a method that returns a reference to the bound service instance. With a reference to this instance, the client can then access data and call methods within the bound service directly.

For the purposes of this example, therefore, some changes are needed to the template BoundService class created in the preceding section. In the first instance, a Binder subclass needs to be declared. This class will contain a single method named getService() which will simply return a reference to the current service object instance (represented by the this keyword). With these requirements in mind, edit the BoundService...

60.6 Binding the Client to the Service

For the purposes of this tutorial, the client is the MainActivity instance of the running application. As previously noted, in order to successfully bind to a service and receive the IBinder object returned by the service’s onBind() method, it is necessary to create a ServiceConnection subclass and implement onServiceConnected() and onServiceDisconnected() callback methods. Edit the MainActivity.java file and modify it as follows:

package com.ebookfrenzy.localbound;

 

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.os.IBinder;

import android.content.Context;

import android.content.Intent;

import android.content.ComponentName;

import android.content.ServiceConnection;

import com.ebookfrenzy.localbound.BoundService.MyLocalBinder;

 

public class MainActivity extends AppCompatActivity {

 

    BoundService myService;

 ...

60.7 Completing the Example

All that remains is to implement a mechanism for calling the getCurrentTime() method and displaying the result to the user. As is now customary, Android Studio will have created a template activity_main.xml file for the activity containing only a TextView. Load this file into the Layout Editor tool and, using Design mode, select the TextView component and change the ID to myTextView. Add a Button view beneath the TextView and change the text on the button to read “Show Time”, extracting the text to a string resource named show_time. On completion of these changes, the layout should resemble that illustrated in Figure 60-1. If any constraints are missing, click on the Infer Constraints button in the Layout Editor toolbar.

Figure 60-1

Complete the user interface design by selecting the Button and configuring the onClick property to call a method named showTime.

Finally, edit the code in the MainActivity.java file to implement the...

60.8 Testing the Application

With the code changes complete, perform a test run of the application. Once visible, touch the button and note that the text view changes to display the current date and time. The example has successfully started and bound to a service and then called a method of that service to cause a task to be performed and results returned to the activity.

60.9 Summary

When a bound service is local and private to an application, components within that application can interact with the service without the need to resort to inter-process communication (IPC). In general terms, the service’s onBind() method returns an IBinder object containing a reference to the instance of the running service. The client component implements a ServiceConnection subclass containing callback methods that are called when the service is connected and disconnected. The former method is passed the IBinder object returned by the onBind() method allowing public methods within the service to be called.

Having covered the implementation of local bound services, the next chapter will focus on using IPC to interact with remote bound services.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth