Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android Studio 4.1 Development Essentials – Kotlin Edition

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

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801815987
Pages 822 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (95) Chapters

1. Introduction 2. Setting up an Android Studio Development Environment 3. Creating an Example Android App in Android Studio 4. Creating an Android Virtual Device (AVD) in Android Studio 5. Using and Configuring the Android Studio AVD Emulator 6. A Tour of the Android Studio User Interface 7. Testing Android Studio Apps on a Physical Android Device 8. The Basics of the Android Studio Code Editor 9. An Overview of the Android Architecture 10. The Anatomy of an Android Application 11. An Introduction to Kotlin 12. Kotlin Data Types,Variables and Nullability 13. Kotlin Operators and Expressions 14. Kotlin Flow Control 15. An Overview of Kotlin Functions and Lambdas 16. The Basics of Object Oriented Programming in Kotlin 17. An Introduction to Kotlin Inheritance and Subclassing 18. An Overview of Android View Binding 19. Understanding Android Application and Activity Lifecycles 20. Handling Android Activity State Changes 21. Android Activity State Changes by Example 22. Saving and Restoring the State of an Android Activity 23. Understanding Android Views, View Groups and Layouts 24. A Guide to the Android Studio Layout Editor Tool 25. A Guide to the Android ConstraintLayout 26. A Guide to using ConstraintLayout in Android Studio 27. Working with ConstraintLayout Chains and Ratios in Android Studio 28. An Android Studio Layout Editor ConstraintLayout Tutorial 29. Manual XML Layout Design in Android Studio 30. Managing Constraints using Constraint Sets 31. An Android ConstraintSet Tutorial 32. A Guide to using Apply Changes in Android Studio 33. An Overview and Example of Android Event Handling 34. Android Touch and Multi-touch Event Handling 35. Detecting Common Gestures using the Android Gesture Detector Class 36. Implementing Custom Gesture and Pinch Recognition on Android 37. An Introduction to Android Fragments 38. Using Fragments in Android Studio - An Example 39. Modern Android App Architecture with Jetpack 40. An Android Jetpack ViewModel Tutorial 41. An Android Jetpack LiveData Tutorial 42. An Overview of Android Jetpack Data Binding 43. An Android Jetpack Data Binding Tutorial 44. An Android ViewModel Saved State Tutorial 45. Working with Android Lifecycle-Aware Components 46. An Android Jetpack Lifecycle Awareness Tutorial 47. An Overview of the Navigation Architecture Component 48. An Android Jetpack Navigation Component Tutorial 49. An Introduction to MotionLayout 50. An Android MotionLayout Editor Tutorial 51. A MotionLayout KeyCycle Tutorial 52. Working with the Floating Action Button and Snackbar 53. Creating a Tabbed Interface using the TabLayout Component 54. Working with the RecyclerView and CardView Widgets 55. An Android RecyclerView and CardView Tutorial 56. A Layout Editor Sample Data Tutorial 57. Working with the AppBar and Collapsing Toolbar Layouts 58. An Android Studio Master/Detail Flow Tutorial 59. An Overview of Android Intents 60. Android Explicit Intents – A Worked Example 61. Android Implicit Intents – A Worked Example 62. Android Broadcast Intents and Broadcast Receivers 63. A Basic Overview of Threads and AsyncTasks 64. An Introduction to Kotlin Coroutines 65. An Android Kotlin Coroutines Tutorial 66. An Overview of Android Started and Bound Services 67. Implementing an Android Started Service – A Worked Example 68. Android Local Bound Services – A Worked Example 69. Android Remote Bound Services – A Worked Example 70. An Android Notifications Tutorial 71. An Android Direct Reply Notification Tutorial 72. Foldable Devices and Multi-Window Support 73. An Overview of Android SQLite Databases 74. The Android Room Persistence Library 75. An Android TableLayout and TableRow Tutorial 76. An Android Room Database and Repository Tutorial 77. Accessing Cloud Storage using the Android Storage Access Framework 78. An Android Storage Access Framework Example 79. Video Playback on Android using the VideoView and MediaController Classes 80. Android Picture-in-Picture Mode 81. An Android Picture-in-Picture Tutorial 82. Making Runtime Permission Requests in Android 83. Android Audio Recording and Playback using MediaPlayer and MediaRecorder 84. Printing with the Android Printing Framework 85. An Android HTML and Web Content Printing Example 86. A Guide to Android Custom Document Printing 87. An Introduction to Android App Links 88. An Android Studio App Links Tutorial 89. A Guide to the Android Studio Profiler 90. An Android Biometric Authentication Tutorial 91. Creating, Testing and Uploading an Android App Bundle 92. An Overview of Android Dynamic Feature Modules 93. An Android Studio Dynamic Feature Tutorial 94. An Overview of Gradle in Android Studio Index

93. 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.

93.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 Kotlin.

93.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) together with the Kotlin extensions plugin:

plugins {

    id 'com.android.application'

    id 'kotlin-android'

    id 'kotlin-android-extensions'

}

.

.

dependencies {

.

.

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

93.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 93-1 below.

Figure 93-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...

93.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 93-2:

Figure 93-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 93-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...

93.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 93-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...

93.6 Adding the Dynamic Feature Activity

From the Project tool window illustrated in Figure 93-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 93-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...

93.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.kt file, make...

93.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.

...

93.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.kt file, add the installFeature() method as follows:

.

.

import android.widget.Toast

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

.

.

   fun installFeature(view: View) {

 

        val request = SplitInstallRequest.newBuilder()

            .addModule("my_dynamic_feature")

            .build()

 

        manager.startInstall(request...

93.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.kt 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.SplitInstallStateUpdatedListener

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

.

.

import java.util.*

.

.

class MainActivity : AppCompatActivity() {

 

    private lateinit var manager: SplitInstallManager

   ...

93.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.app.Activity

import android.content.IntentSender

.

.

class MainActivity : AppCompatActivity() {

.

.

    private val REQUESTCODE = 101

.

.

   private var listener: SplitInstallStateUpdatedListener =

        SplitInstallStateUpdatedListener { state ->

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

                when (state.status()) {

 

                    SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION...

93.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:

fun 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.

93.13 Removing a Dynamic Module

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

fun deleteFeature(view: View) {

    manager.deferredUninstall(Arrays.asList("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.

93.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 – Kotlin Edition
Published in: May 2021 Publisher: Packt ISBN-13: 9781801815987
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.
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}