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

86. An Android Studio Dynamic Feature Tutorial

With the basic concepts of Android Dynamic Delivery and Dynamic Features covered in the previous chapter, this chapter will put this theory into practice in the form of an example project. The app created in this chapter will consist of two activities, the first of which will serve as the base module for the app while the second will be designated as a dynamic feature to be downloaded on demand from within the running app. This tutorial will include steps to create a dynamic module from within Android Studio, upload the app bundle to the Google Play Store for testing, and use the Play Core Library to download and manage dynamic features. The chapter will also explore the use of deferred dynamic feature installation.

86.1 Creating the DynamicFeature Project

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 DynamicFeature into the Name field and specify a package name that will uniquely identify your app within the Google Play ecosystem (for example com.<your company>.dynamicfeature) 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.

86.2 Adding Dynamic Feature Support to the Project

Before embarking on the implementation of the app, two changes need to be made to the project to add support for dynamic features. Since the project will be making extensive use of the Play Core Library, a directive needs to be added to the build configuration to include this library. Within Android Studio, open the app level build.gradle file (Gradle Scripts -> build.gradle (Module: DynamicFeature.app)), locate the dependencies section and add the Play Core Library as follows (keeping in mind, as always, that a newer version of the library may now be available):

.

.

dependencies {

.

.

    implementation 'com.google.android.play:core:1.8.0'

.

.

}

Once a dynamic feature module has been downloaded, it is most likely that immediate access to code and resource assets that comprise the feature will be required by the user. By default, however, newly installed feature modules...

86.3 Designing the Base Activity User Interface

At this point, the project consists of a single activity which will serve as the entry point for the base module of the app. This base module will be responsible for requesting, installing and managing the dynamic feature module.

To demonstrate the use of dynamic features, the base activity will consist of a series of buttons which will allow the dynamic feature module to be installed, launched and removed. The user interface will also include a TextView object to display status information relating to the dynamic feature module. With these requirements in mind, load the activity_main.xml layout file into the layout editor, delete the default TextView object, and implement the design so that it resembles Figure 86-1 below.

Figure 86-1

Once the objects have been positioned, select the TextView widget and use the Attributes tool window to set the id property to status_text. Begin applying layout constraints by selecting all...

86.4 Adding the Dynamic Feature Module

To add a dynamic feature module to the project, select the File -> New -> New Module... menu option and, in the resulting dialog, choose the Dynamic Feature Module option as shown in Figure 86-2:

Figure 86-2

With the Dynamic Feature Module option selected, click on the Next button and, in the configuration screen, name the module my_dynamic_feature and change the minimum API setting to API 26: Android 8.0 (Oreo) so that it matches the API level chosen for the base module:

Click the Next button once more to configure the On-Demand options, making sure that the Fusing option is enabled. In the Module Title field, enter text which reads “My Example Dynamic Feature”:

Figure 86-3

For the purposes of this example, set the Install-time inclusion menu to Do not include module at install time (on-demand only) before clicking on the Finish button to commit the changes and add the dynamic feature module to the...

86.5 Reviewing the Dynamic Feature Module

Before proceeding to the next step, it is worth taking some time to review the changes that have been made to the project by Android Studio. Understanding these changes can be useful both when resolving problems and when converting existing app features to dynamic features.

Begin by referring to the Project tool window, where a new entry will have appeared representing the folder containing the new dynamic feature module:

Figure 86-4

Note that the feature has its own sub-structure including a manifest file, a package into which code and resources can be added and a res folder. Open and review the AndroidManifest.xml file which should contain the property settings that were selected during the feature creation process including the on-demand, fusing and feature title values:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:dist="http://schemas.android.com...

86.6 Adding the Dynamic Feature Activity

From the Project tool window illustrated in Figure 86-4 above, it is clear that the dynamic feature module contains little more than a manifest file at this point. The next step is to add an activity to the module so that the feature actually does something when launched from within the base module. Within the Project tool window, right-click on the package name located under my_dynamic_feature -> java and select the New -> Activity -> Empty Activity menu option. Name the activity MyFeatureActivity and enable the Generate Layout File option but leave the Launcher Activity option disabled before clicking on the Finish button.

Figure 86-5

Once the activity has been added to the module, edit the AndroidManifest.xml file and modify it to add an intent filter that will allow the activity to be launched by the base module (where <com.yourcompany> is replaced by the package name you chose in order to make your app unique on...

86.7 Implementing the launchIntent() Method

With the project structure and user interface designs completed it is time to use the Play Core Library to begin working with the dynamic feature module. The first step is to implement the launchFeature() method, the purpose of which is to use an intent to launch the dynamic feature activity. Attempting to start an activity in a dynamic feature module that has yet to be installed, however, will cause the app to crash. The launchFeature() method, therefore, needs to include some defensive code to ensure that the dynamic feature has been installed. To achieve this, we need to create an instance of the SplitInstallManager class and call the getInstalledModules() method of that object to check whether the my_dynamic_feature module is already installed. If it is installed, the activity contained in the module can be safely launched, otherwise a message needs to be displayed to the user on the status TextView. Within the MainActivity.java file...

86.8 Uploading the App Bundle for Testing

The project is now ready for the first phase of testing. This involves generating a release app bundle and uploading it to the Google Play Console. The steps to achieve this were outlined in the chapter entitled “Creating, Testing and Uploading an Android App Bundle” but can be summarized as follows:

1. Log into the Google Play Console and create a new application.

2. Work through the steps to configure the app in terms of title, descriptions, categorization and image assets (sample image assets can be found in the image_assets folder of the sample code download that accompanies this book) and save the draft settings. Also be sure to enable Google Play app signing for the bundle.

3. Use the Android Studio Build -> Generate Signed App Bundle / APK... menu to generate a signed release app bundle.

4. In the Google Play Console, select the Testing -> Internal testing option from the left hand navigation panel.

...

86.9 Implementing the installFeature() Method

The installFeature() method will create a SplitInstallRequest object for the my_dynamic_feature module, then use the SplitInstallManager instance to initiate the installation process. Listeners will also be implemented to display Toast messages indicating the status of the install request. Remaining in the MainActivity.java file, add the installFeature() method as follows:

.

.

import android.widget.Toast;

.

.

import com.google.android.play.core.splitinstall.SplitInstallRequest;

import com.google.android.play.core.tasks.OnFailureListener;

import com.google.android.play.core.tasks.OnSuccessListener;

.

.

    public void installFeature(View view) {

 

        SplitInstallRequest request =

                SplitInstallRequest

     ...

86.10 Adding the Update Listener

For more detailed tracking of the installation progress of a dynamic feature module, an instance of SplitInstallStateUpdatedListener can be added to the app. Since it is possible to install multiple feature modules simultaneously, some code needs to be added to keep track of the session IDs assigned to the installation processes. Begin by adding some imports, declaring a variable in the MainActivity.java file to contain the current session ID and modifying the installFeature() method to store the session ID each time an installation is successfully started and to register the listener:

.

.

import com.google.android.play.core.splitinstall.SplitInstallSessionState;

import

     com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener;

import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus;

.

.

import java.util.Locale;

.

.

public class MainActivity...

86.11 Handling Large Downloads

The next task for this project is to integrate support for large feature modules by adding an additional case to the switch statement in the listener implementation as follows:

.

.

import android.content.IntentSender;

.

.

public class MainActivity extends AppCompatActivity {

.

.

    private static final int REQUEST_CODE = 101;

.

.

SplitInstallStateUpdatedListener listener =

                        new SplitInstallStateUpdatedListener() {

    @Override

    public void onStateUpdate(SplitInstallSessionState state) {

 

        if (state.sessionId() == mySessionId) {

            switch (state.status()) {

 

 ...

86.12 Using Deferred Installation

Deferred installation causes dynamic feature modules to be downloaded in the background and will be completed at the discretion of the operating system. When a deferred installation is initiated, the listener will be called with a pending status, but it is not otherwise possible to track the progress of the installation aside from checking whether or not the module has been installed.

To try deferred installation, modify the installFeature() method so that it reads as follows:

public void installFeature(View view) {

 manager.deferredInstall(Arrays.asList("my_dynamic_feature"));

}

Note that the deferredInstall() method is passed an array, allowing the installation of multiple modules to be deferred.

86.13 Removing a Dynamic Module

The final task in this project is to implement the deleteFeature() method as follows in the MainActivity.java file:

.

.

import java.util.Arrays;

.

.

public void deleteFeature(View view) {

    manager.deferredUninstall(Collections.singletonList("my_dynamic_feature"));

}

The removal of the feature will be performed in the background by the operating system when additional storage space is needed. As with the deferredInstall() method, multiple features may be scheduled for removal in a single call.

86.14 Summary

This chapter has worked through the creation of an example app designed to demonstrate the use of dynamic feature modules within an Android app. Topics covered included the creation of a dynamic feature module and the use of the classes and methods of the Play Core Library to install and manage a dynamic feature module.

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