Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Android Studio Meerkat Essentials - Kotlin Edition: Developing Android Apps Using Android Studio Meerkat and Kotlin
Android Studio Meerkat Essentials - Kotlin Edition: Developing Android Apps Using Android Studio Meerkat and Kotlin
Android Studio Meerkat Essentials - Kotlin Edition: Developing Android Apps Using Android Studio Meerkat and Kotlin
Ebook1,897 pages11 hours

Android Studio Meerkat Essentials - Kotlin Edition: Developing Android Apps Using Android Studio Meerkat and Kotlin

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book, fully updated for Android Studio Meerkat and the new UI, teaches you how to develop Android-based applications using Kotlin.


Beginning with the basics, the book outlines how to set up an Android development and testing environment, followed by an introduction to programming in Kotlin, including data types, control flow, functions, lambdas, and object-oriented programming. Asynchronous programming using Kotlin coroutines and flow is also covered in detail.


Chapters also cover the Android Architecture Components, including view models, lifecycle management, Room database access, content providers, the Database Inspector, app navigation, live data, and data binding.


More advanced topics, such as intents, are also covered, such as touchscreen handling, gesture recognition, and the recording and playback of audio. This book edition also covers printing, transitions, and foldable device support.


The concepts of material design are also covered in detail, including the use of floating action buttons, Snackbars, tabbed interfaces, card views, navigation drawers, and collapsing toolbars.


Other key features of Android Studio and Android are also covered in detail, including the Layout Editor, the ConstraintLayout and ConstraintSet classes, view binding, constraint chains, barriers, and direct reply notifications.


Chapters also cover advanced features of Android Studio, such as Gradle build configuration, in-app billing, and submitting apps to the Google Play Developer Console.


Assuming you already have some programming experience, are ready to download Android Studio and the Android SDK, have access to a Windows, Mac, or Linux system, and have ideas for some apps to develop, you are ready to get started.

LanguageEnglish
PublisherPayload Publishing
Release dateApr 3, 2025
Android Studio Meerkat Essentials - Kotlin Edition: Developing Android Apps Using Android Studio Meerkat and Kotlin

Read more from Neil Smyth

Related to Android Studio Meerkat Essentials - Kotlin Edition

Related ebooks

Programming For You

View More

Reviews for Android Studio Meerkat Essentials - Kotlin Edition

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Android Studio Meerkat Essentials - Kotlin Edition - Neil Smyth

    Cover of Android Studio Meerkat Essentials - Kotlin Edition by Neil Smyth

    Android Studio Meerkat

    Essentials

    Kotlin Edition

    Android Studio Meerkat Essentials – Kotlin Edition

    © 2025 Neil Smyth / Payload Media, Inc. All Rights Reserved.

    This book is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited. All rights reserved.

    The content of this book is provided for informational purposes only. Neither the publisher nor the author offers any warranties or representation, express or implied, with regard to the accuracy of information contained in this book, nor do they accept any liability for any loss or damage arising from any errors or omissions.

    This book contains trademarked terms that are used solely for editorial purposes and to the benefit of the respective trademark owner. The terms used within this book are not intended as infringement of any trademarks.

    Rev: 1.0

    https://www.payloadbooks.com

    Copyright

    "

    Table of Contents

    1. Introduction

    1.1 Downloading the Code Samples

    1.2 Feedback

    1.3 Errata

    2. Setting up an Android Studio Development Environment

    2.1 System requirements

    2.2 Downloading the Android Studio package

    2.3 Installing Android Studio

    2.3.1 Installation on Windows

    2.3.2 Installation on macOS

    2.3.3 Installation on Linux

    2.4 The Android Studio setup wizard

    2.5 Installing additional Android SDK packages

    2.6 Installing the Android SDK Command-line Tools

    2.6.1 Windows 8.1

    2.6.2 Windows 10

    2.6.3 Windows 11

    2.6.4 Linux

    2.6.5 macOS

    2.7 Android Studio memory management

    2.8 Updating Android Studio and the SDK

    2.9 Summary

    3. Creating an Example Android App in Android Studio

    3.1 About the Project

    3.2 Creating a New Android Project

    3.3 Creating an Activity

    3.4 Defining the Project and SDK Settings

    3.5 Modifying the Example Application

    3.6 Modifying the User Interface

    3.7 Reviewing the Layout and Resource Files

    3.8 Adding Interaction

    3.9 Summary

    4. Creating an Android Virtual Device (AVD) in Android Studio

    4.1 About Android Virtual Devices

    4.2 Starting the Emulator

    4.3 Running the Application in the AVD

    4.4 Running on Multiple Devices

    4.5 Stopping a Running Application

    4.6 Running the Emulator in a Separate Window

    4.7 Removing the Device Frame

    4.8 Summary

    5. Using and Configuring the Android Studio AVD Emulator

    5.1 The Emulator Environment

    5.2 Emulator Toolbar Options

    5.3 Working in Zoom Mode

    5.4 Resizing the Emulator Window

    5.5 Extended Control Options

    5.5.1 Displays

    5.5.2 Cellular

    5.5.3 Battery

    5.5.4 Camera

    5.5.5 Location

    5.5.6 Phone

    5.5.7 Directional Pad

    5.5.8 Microphone

    5.5.9 Fingerprint

    5.5.10 Virtual Sensors

    5.5.11 Snapshots

    5.5.12 Record and Playback

    5.5.13 Google Play

    5.5.14 Settings

    5.5.15 Help

    5.6 Working with Snapshots

    5.7 Configuring Fingerprint Emulation

    5.8 The Emulator in Tool Window Mode

    5.9 Common Android Settings

    5.10 Creating a Resizable Emulator

    5.11 Summary

    6. A Tour of the Android Studio User Interface

    6.1 The Welcome Screen

    6.2 The Menu Bar

    6.3 The Main Window

    6.4 The Tool Windows

    6.5 The Tool Window Menus

    6.6 Android Studio Keyboard Shortcuts

    6.7 Switcher and Recent Files Navigation

    6.8 Changing the Android Studio Theme

    6.9 Summary

    7. Testing Android Studio Apps on a Physical Android Device

    7.1 An Overview of the Android Debug Bridge (ADB)

    7.2 Enabling USB Debugging ADB on Android Devices

    7.2.1 macOS ADB Configuration

    7.2.2 Windows ADB Configuration

    7.2.3 Linux adb Configuration

    7.3 Resolving USB Connection Issues

    7.4 Enabling Wireless Debugging on Android Devices

    7.5 Testing the adb Connection

    7.6 Device Mirroring

    7.7 Summary

    8. The Basics of the Android Studio Code Editor

    8.1 The Android Studio Editor

    8.2 The Floating Code Toolbar

    8.3 Splitting the Editor Window

    8.4 Code Completion

    8.5 Statement Completion

    8.6 Parameter Information

    8.7 Parameter Name Hints

    8.8 Code Generation

    8.9 Code Folding

    8.10 Quick Documentation Lookup

    8.11 Code Reformatting

    8.12 Finding Sample Code

    8.13 Live Templates

    8.14 Summary

    9. An Overview of the Android Architecture

    9.1 The Android Software Stack

    9.2 The Linux Kernel

    9.3 Hardware Abstraction Layer

    9.4 Android Runtime – ART

    9.5 Android Libraries

    9.5.1 C/C++ Libraries

    9.6 Application Framework

    9.7 Applications

    9.8 Summary

    10. The Anatomy of an Android App

    10.1 Android Activities

    10.2 Android Fragments

    10.3 Android Intents

    10.4 Broadcast Intents

    10.5 Broadcast Receivers

    10.6 Android Services

    10.7 Content Providers

    10.8 The Application Manifest

    10.9 Application Resources

    10.10 Application Context

    10.11 Summary

    11. An Introduction to Kotlin

    11.1 What is Kotlin?

    11.2 Kotlin and Java

    11.3 Converting from Java to Kotlin

    11.4 Kotlin and Android Studio

    11.5 Experimenting with Kotlin

    11.6 Semi-colons in Kotlin

    11.7 Summary

    12. Kotlin Data Types, Variables, and Nullability

    12.1 Kotlin Data Types

    12.1.1 Integer Data Types

    12.1.2 Floating-Point Data Types

    12.1.3 Boolean Data Type

    12.1.4 Character Data Type

    12.1.5 String Data Type

    12.1.6 Escape Sequences

    12.2 Mutable Variables

    12.3 Immutable Variables

    12.4 Declaring Mutable and Immutable Variables

    12.5 Data Types are Objects

    12.6 Type Annotations and Type Inference

    12.7 Nullable Type

    12.8 The Safe Call Operator

    12.9 Not-Null Assertion

    12.10 Nullable Types and the let Function

    12.11 Late Initialization (lateinit)

    12.12 The Elvis Operator

    12.13 Type Casting and Type Checking

    12.14 Summary

    13. Kotlin Operators and Expressions

    13.1 Expression Syntax in Kotlin

    13.2 The Basic Assignment Operator

    13.3 Kotlin Arithmetic Operators

    13.4 Augmented Assignment Operators

    13.5 Increment and Decrement Operators

    13.6 Equality Operators

    13.7 Boolean Logical Operators

    13.8 Range Operator

    13.9 Bitwise Operators

    13.9.1 Bitwise Inversion

    13.9.2 Bitwise AND

    13.9.3 Bitwise OR

    13.9.4 Bitwise XOR

    13.9.5 Bitwise Left Shift

    13.9.6 Bitwise Right Shift

    13.10 Summary

    14. Kotlin Control Flow

    14.1 Looping Control flow

    14.1.1 The Kotlin for-in Statement

    14.1.2 The while Loop

    14.1.3 The do ... while loop

    14.1.4 Breaking from Loops

    14.1.5 The continue Statement

    14.1.6 Break and Continue Labels

    14.2 Conditional Control Flow

    14.2.1 Using the if Expressions

    14.2.2 Using if ... else … Expressions

    14.2.3 Using if ... else if ... Expressions

    14.2.4 Using the when Statement

    14.3 Summary

    15. An Overview of Kotlin Functions and Lambdas

    15.1 What is a Function?

    15.2 How to Declare a Kotlin Function

    15.3 Calling a Kotlin Function

    15.4 Single Expression Functions

    15.5 Local Functions

    15.6 Handling Return Values

    15.7 Declaring Default Function Parameters

    15.8 Variable Number of Function Parameters

    15.9 Lambda Expressions

    15.10 Higher-order Functions

    15.11 Summary

    16. The Basics of Object Oriented Programming in Kotlin

    16.1 What is an Object?

    16.2 What is a Class?

    16.3 Declaring a Kotlin Class

    16.4 Adding Properties to a Class

    16.5 Defining Methods

    16.6 Declaring and Initializing a Class Instance

    16.7 Primary and Secondary Constructors

    16.8 Initializer Blocks

    16.9 Calling Methods and Accessing Properties

    16.10 Custom Accessors

    16.11 Nested and Inner Classes

    16.12 Companion Objects

    16.13 Summary

    17. An Introduction to Kotlin Inheritance and Subclassing

    17.1 Inheritance, Classes and Subclasses

    17.2 Subclassing Syntax

    17.3 A Kotlin Inheritance Example

    17.4 Extending the Functionality of a Subclass

    17.5 Overriding Inherited Methods

    17.6 Adding a Custom Secondary Constructor

    17.7 Using the SavingsAccount Class

    17.8 Summary

    18. An Overview of Android View Binding

    18.1 Find View by Id

    18.2 View Binding

    18.3 Converting the AndroidSample project

    18.4 Enabling View Binding

    18.5 Using View Binding

    18.6 Choosing an Option

    18.7 View Binding in the Book Examples

    18.8 Migrating a Project to View Binding

    18.9 Summary

    19. Introducing Gemini in Android Studio

    19.1 Introducing Gemini AI

    19.2 Enabling Gemini in Android Studio

    19.3 Gemini configuration

    19.4 Asking Gemini questions

    19.5 Question contexts

    19.6 Inline code completion

    19.7 Transforming and documenting code

    19.8 Smart renaming

    19.9 Summary

    20. Understanding Android Application and Activity Lifecycles

    20.1 Android Applications and Resource Management

    20.2 Android Process States

    20.2.1 Foreground Process

    20.2.2 Visible Process

    20.2.3 Service Process

    20.2.4 Background Process

    20.2.5 Empty Process

    20.3 Inter-Process Dependencies

    20.4 The Activity Lifecycle

    20.5 The Activity Stack

    20.6 Activity States

    20.7 Configuration Changes

    20.8 Handling State Change

    20.9 Summary

    21. Handling Android Activity State Changes

    21.1 New vs. Old Lifecycle Techniques

    21.2 The Activity and Fragment Classes

    21.3 Dynamic State vs. Persistent State

    21.4 The Android Lifecycle Methods

    21.5 Lifetimes

    21.6 Foldable Devices and Multi-Resume

    21.7 Disabling Configuration Change Restarts

    21.8 Lifecycle Method Limitations

    21.9 Summary

    22. Android Activity State Changes by Example

    22.1 Creating the State Change Example Project

    22.2 Designing the User Interface

    22.3 Overriding the Activity Lifecycle Methods

    22.4 Filtering the Logcat Panel

    22.5 Running the Application

    22.6 Experimenting with the Activity

    22.7 Summary

    23. Saving and Restoring the State of an Android Activity

    23.1 Saving Dynamic State

    23.2 Default Saving of User Interface State

    23.3 The Bundle Class

    23.4 Saving the State

    23.5 Restoring the State

    23.6 Testing the Application

    23.7 Summary

    24. Understanding Android Views, View Groups and Layouts

    24.1 Designing for Different Android Devices

    24.2 Views and View Groups

    24.3 Android Layout Managers

    24.4 The View Hierarchy

    24.5 Creating User Interfaces

    24.6 Summary

    25. A Guide to the Android Studio Layout Editor Tool

    25.1 Basic vs. Empty Views Activity Templates

    25.2 The Android Studio Layout Editor

    25.3 Design Mode

    25.4 The Palette

    25.5 Design Mode and Layout Views

    25.6 Night Mode

    25.7 Code Mode

    25.8 Split Mode

    25.9 Setting Attributes

    25.10 Transforms

    25.11 Tools Visibility Toggles

    25.12 Converting Views

    25.13 Displaying Sample Data

    25.14 Creating a Custom Device Definition

    25.15 Changing the Current Device

    25.16 Layout Validation

    25.17 Summary

    26. A Guide to the Android ConstraintLayout

    26.1 How ConstraintLayout Works

    26.1.1 Constraints

    26.1.2 Margins

    26.1.3 Opposing Constraints

    26.1.4 Constraint Bias

    26.1.5 Chains

    26.1.6 Chain Styles

    26.2 Baseline Alignment

    26.3 Configuring Widget Dimensions

    26.4 Guideline Helper

    26.5 Group Helper

    26.6 Barrier Helper

    26.7 Flow Helper

    26.8 Ratios

    26.9 ConstraintLayout Advantages

    26.10 ConstraintLayout Availability

    26.11 Summary

    27. A Guide to Using ConstraintLayout in Android Studio

    27.1 Design and Layout Views

    27.2 Autoconnect Mode

    27.3 Inference Mode

    27.4 Manipulating Constraints Manually

    27.5 Adding Constraints in the Inspector

    27.6 Viewing Constraints in the Attributes Window

    27.7 Deleting Constraints

    27.8 Adjusting Constraint Bias

    27.9 Understanding ConstraintLayout Margins

    27.10 The Importance of Opposing Constraints and Bias

    27.11 Configuring Widget Dimensions

    27.12 Design Time Tools Positioning

    27.13 Adding Guidelines

    27.14 Adding Barriers

    27.15 Adding a Group

    27.16 Working with the Flow Helper

    27.17 Widget Group Alignment and Distribution

    27.18 Converting other Layouts to ConstraintLayout

    27.19 Summary

    28. Working with ConstraintLayout Chains and Ratios in Android Studio

    28.1 Creating a Chain

    28.2 Changing the Chain Style

    28.3 Spread Inside Chain Style

    28.4 Packed Chain Style

    28.5 Packed Chain Style with Bias

    28.6 Weighted Chain

    28.7 Working with Ratios

    28.8 Summary

    29. An Android Studio Layout Editor ConstraintLayout Tutorial

    29.1 An Android Studio Layout Editor Tool Example

    29.2 Preparing the Layout Editor Environment

    29.3 Adding the Widgets to the User Interface

    29.4 Adding the Constraints

    29.5 Testing the Layout

    29.6 Using the Layout Inspector

    29.7 Summary

    30. Manual XML Layout Design in Android Studio

    30.1 Manually Creating an XML Layout

    30.2 Manual XML vs. Visual Layout Design

    30.3 Summary

    31. Managing Constraints using Constraint Sets

    31.1 Kotlin Code vs. XML Layout Files

    31.2 Creating Views

    31.3 View Attributes

    31.4 Constraint Sets

    31.4.1 Establishing Connections

    31.4.2 Applying Constraints to a Layout

    31.4.3 Parent Constraint Connections

    31.4.4 Sizing Constraints

    31.4.5 Constraint Bias

    31.4.6 Alignment Constraints

    31.4.7 Copying and Applying Constraint Sets

    31.4.8 ConstraintLayout Chains

    31.4.9 Guidelines

    31.4.10 Removing Constraints

    31.4.11 Scaling

    31.4.12 Rotation

    31.5 Summary

    32. An Android ConstraintSet Tutorial

    32.1 Creating the Example Project in Android Studio

    32.2 Adding Views to an Activity

    32.3 Setting View Attributes

    32.4 Creating View IDs

    32.5 Configuring the Constraint Set

    32.6 Adding the EditText View

    32.7 Converting Density Independent Pixels (dp) to Pixels (px)

    32.8 Summary

    33. A Guide to Using Apply Changes in Android Studio

    33.1 Introducing Apply Changes

    33.2 Understanding Apply Changes Options

    33.3 Using Apply Changes

    33.4 Configuring Apply Changes Fallback Settings

    33.5 An Apply Changes Tutorial

    33.6 Using Apply Code Changes

    33.7 Using Apply Changes and Restart Activity

    33.8 Using Run App

    33.9 Summary

    34. A Guide to Gradle Version Catalogs

    34.1 Library and Plugin Dependencies

    34.2 Project Gradle Build File

    34.3 Module Gradle Build Files

    34.4 Version Catalog File

    34.5 Adding Dependencies

    34.6 Library Updates

    34.7 Summary

    35. An Overview and Example of Android Event Handling

    35.1 Understanding Android Events

    35.2 Using the android:onClick Resource

    35.3 Event Listeners and Callback Methods

    35.4 An Event Handling Example

    35.5 Designing the User Interface

    35.6 The Event Listener and Callback Method

    35.7 Consuming Events

    35.8 Summary

    36. Android Touch and Multi-touch Event Handling

    36.1 Intercepting Touch Events

    36.2 The MotionEvent Object

    36.3 Understanding Touch Actions

    36.4 Handling Multiple Touches

    36.5 An Example Multi-Touch Application

    36.6 Designing the Activity User Interface

    36.7 Implementing the Touch Event Listener

    36.8 Running the Example Application

    36.9 Summary

    37. Detecting Common Gestures Using the Android Gesture Detector Class

    37.1 Implementing Common Gesture Detection

    37.2 Creating an Example Gesture Detection Project

    37.3 Implementing the Listener Class

    37.4 Creating the GestureDetector Instance

    37.5 Implementing the onTouchEvent() Method

    37.6 Testing the Application

    37.7 Summary

    38. Implementing Custom Gesture and Pinch Recognition on Android

    38.1 The Android Gesture Builder Application

    38.2 The GestureOverlayView Class

    38.3 Detecting Gestures

    38.4 Identifying Specific Gestures

    38.5 Installing and Running the Gesture Builder Application

    38.6 Creating a Gestures File

    38.7 Creating the Example Project

    38.8 Extracting the Gestures File from the SD Card

    38.9 Adding the Gestures File to the Project

    38.10 Designing the User Interface

    38.11 Loading the Gestures File

    38.12 Registering the Event Listener

    38.13 Implementing the onGesturePerformed Method

    38.14 Testing the Application

    38.15 Configuring the GestureOverlayView

    38.16 Intercepting Gestures

    38.17 Detecting Pinch Gestures

    38.18 A Pinch Gesture Example Project

    38.19 Summary

    39. An Introduction to Android Fragments

    39.1 What is a Fragment?

    39.2 Creating a Fragment

    39.3 Adding a Fragment to an Activity using the Layout XML File

    39.4 Adding and Managing Fragments in Code

    39.5 Handling Fragment Events

    39.6 Implementing Fragment Communication

    39.7 Summary

    40. Using Fragments in Android Studio - An Example

    40.1 About the Example Fragment Application

    40.2 Creating the Example Project

    40.3 Creating the First Fragment Layout

    40.4 Migrating a Fragment to View Binding

    40.5 Adding the Second Fragment

    40.6 Adding the Fragments to the Activity

    40.7 Making the Toolbar Fragment Talk to the Activity

    40.8 Making the Activity Talk to the Text Fragment

    40.9 Testing the Application

    40.10 Summary

    41. Modern Android App Architecture with Jetpack

    41.1 What is Android Jetpack?

    41.2 The Old Architecture

    41.3 Modern Android Architecture

    41.4 The ViewModel Component

    41.5 The LiveData Component

    41.6 ViewModel Saved State

    41.7 LiveData and Data Binding

    41.8 Android Lifecycles

    41.9 Repository Modules

    41.10 Summary

    42. An Android ViewModel Tutorial

    42.1 About the Project

    42.2 Creating the ViewModel Example Project

    42.3 Removing Unwanted Project Elements

    42.4 Designing the Fragment Layout

    42.5 Implementing the View Model

    42.6 Associating the Fragment with the View Model

    42.7 Modifying the Fragment

    42.8 Accessing the ViewModel Data

    42.9 Testing the Project

    42.10 Summary

    43. An Android Jetpack LiveData Tutorial

    43.1 LiveData - A Recap

    43.2 Adding LiveData to the ViewModel

    43.3 Implementing the Observer

    43.4 Summary

    44. An Overview of Android Jetpack Data Binding

    44.1 An Overview of Data Binding

    44.2 The Key Components of Data Binding

    44.2.1 The Project Build Configuration

    44.2.2 The Data Binding Layout File

    44.2.3 The Layout File Data Element

    44.2.4 The Binding Classes

    44.2.5 Data Binding Variable Configuration

    44.2.6 Binding Expressions (One-Way)

    44.2.7 Binding Expressions (Two-Way)

    44.2.8 Event and Listener Bindings

    44.3 Summary

    45. An Android Jetpack Data Binding Tutorial

    45.1 Removing the Redundant Code

    45.2 Enabling Data Binding

    45.3 Adding the Layout Element

    45.4 Adding the Data Element to Layout File

    45.5 Working with the Binding Class

    45.6 Assigning the ViewModel Instance to the Data Binding Variable

    45.7 Adding Binding Expressions

    45.8 Adding the Conversion Method

    45.9 Adding a Listener Binding

    45.10 Testing the App

    45.11 Summary

    46. An Android ViewModel Saved State Tutorial

    46.1 Understanding ViewModel State Saving

    46.2 Implementing ViewModel State Saving

    46.3 Saving and Restoring State

    46.4 Adding Saved State Support to the ViewModelDemo Project

    46.5 Summary

    47. Working with Android Lifecycle-Aware Components

    47.1 Lifecycle Awareness

    47.2 Lifecycle Owners

    47.3 Lifecycle Observers

    47.4 Lifecycle States and Events

    47.5 Summary

    48. An Android Jetpack Lifecycle Awareness Tutorial

    48.1 Creating the Example Lifecycle Project

    48.2 Creating a Lifecycle Observer

    48.3 Adding the Observer

    48.4 Testing the Observer

    48.5 Creating a Lifecycle Owner

    48.6 Testing the Custom Lifecycle Owner

    48.7 Summary

    49. An Overview of the Navigation Architecture Component

    49.1 Understanding Navigation

    49.2 Declaring a Navigation Host

    49.3 The Navigation Graph

    49.4 Accessing the Navigation Controller

    49.5 Triggering a Navigation Action

    49.6 Passing Arguments

    49.7 Summary

    50. An Android Jetpack Navigation Component Tutorial

    50.1 Creating the NavigationDemo Project

    50.2 Adding Navigation to the Build Configuration

    50.3 Creating the Navigation Graph Resource File

    50.4 Declaring a Navigation Host

    50.5 Adding Navigation Destinations

    50.6 Designing the Destination Fragment Layouts

    50.7 Adding an Action to the Navigation Graph

    50.8 Implement the OnFragmentInteractionListener

    50.9 Adding View Binding Support to the Destination Fragments

    50.10 Triggering the Action

    50.11 Passing Data Using Safeargs

    50.12 Summary

    51. Working with the Floating Action Button and Snackbar

    51.1 The Material Design

    51.2 The Design Library

    51.3 The Floating Action Button (FAB)

    51.4 The Snackbar

    51.5 Creating the Example Project

    51.6 Reviewing the Project

    51.7 Removing Navigation Features

    51.8 Changing the Floating Action Button

    51.9 Adding an Action to the Snackbar

    51.10 Summary

    52. Creating a Tabbed Interface using the TabLayout Component

    52.1 An Introduction to the ViewPager2

    52.2 An Overview of the TabLayout Component

    52.3 Creating the TabLayoutDemo Project

    52.4 Creating the First Fragment

    52.5 Duplicating the Fragments

    52.6 Adding the TabLayout and ViewPager2

    52.7 Performing the Initialization Tasks

    52.8 Testing the Application

    52.9 Customizing the TabLayout

    52.10 Summary

    53. Working with the RecyclerView and CardView Widgets

    53.1 An Overview of the RecyclerView

    53.2 An Overview of the CardView

    53.3 Summary

    54. An Android RecyclerView and CardView Tutorial

    54.1 Creating the CardDemo Project

    54.2 Modifying the Basic Views Activity Project

    54.3 Designing the CardView Layout

    54.4 Adding the RecyclerView

    54.5 Adding the Image Files

    54.6 Creating the RecyclerView Adapter

    54.7 Initializing the RecyclerView Component

    54.8 Testing the Application

    54.9 Responding to Card Selections

    54.10 Summary

    55. Working with the AppBar and Collapsing Toolbar Layouts

    55.1 The Anatomy of an AppBar

    55.2 The Example Project

    55.3 Coordinating the RecyclerView and Toolbar

    55.4 Introducing the Collapsing Toolbar Layout

    55.5 Changing the Title and Scrim Color

    55.6 Summary

    56. An Overview of Android Intents

    56.1 An Overview of Intents

    56.2 Explicit Intents

    56.3 Returning Data from an Activity

    56.4 Implicit Intents

    56.5 Using Intent Filters

    56.6 Automatic Link Verification

    56.7 Manually Enabling Links

    56.8 Checking Intent Availability

    56.9 Summary

    57. Android Explicit Intents – A Worked Example

    57.1 Creating the Explicit Intent Example Application

    57.2 Designing the User Interface Layout for MainActivity

    57.3 Creating the Second Activity Class

    57.4 Designing the User Interface Layout for SecondActivity

    57.5 Reviewing the Application Manifest File

    57.6 Creating the Intent

    57.7 Extracting Intent Data

    57.8 Launching SecondActivity as a Sub-Activity

    57.9 Returning Data from a Sub-Activity

    57.10 Testing the Application

    57.11 Summary

    58. Android Implicit Intents – A Worked Example

    58.1 Creating the Android Studio Implicit Intent Example Project

    58.2 Designing the User Interface

    58.3 Creating the Implicit Intent

    58.4 Adding a Second Matching Activity

    58.5 Adding the Web View to the UI

    58.6 Obtaining the Intent URL

    58.7 Modifying the MyWebView Project Manifest File

    58.8 Installing the MyWebView Package on a Device

    58.9 Testing the Application

    58.10 Manually Enabling the Link

    58.11 Automatic Link Verification

    58.12 Summary

    59. Android Broadcast Intents and Broadcast Receivers

    59.1 An Overview of Broadcast Intents

    59.2 An Overview of Broadcast Receivers

    59.3 Obtaining Results from a Broadcast

    59.4 Sticky Broadcast Intents

    59.5 The Broadcast Intent Example

    59.6 Creating the Example Application

    59.7 Creating and Sending the Broadcast Intent

    59.8 Creating the Broadcast Receiver

    59.9 Registering the Broadcast Receiver

    59.10 Testing the Broadcast Example

    59.11 Listening for System Broadcasts

    59.12 Summary

    60. An Introduction to Kotlin Coroutines

    60.1 What are Coroutines?

    60.2 Threads vs. Coroutines

    60.3 Coroutine Scope

    60.4 Suspend Functions

    60.5 Coroutine Dispatchers

    60.6 Coroutine Builders

    60.7 Jobs

    60.8 Coroutines – Suspending and Resuming

    60.9 Returning Results from a Coroutine

    60.10 Using withContext

    60.11 Coroutine Channel Communication

    60.12 Summary

    61. An Android Kotlin Coroutines Tutorial

    61.1 Creating the Coroutine Example Application

    61.2 Designing the User Interface

    61.3 Implementing the SeekBar

    61.4 Adding the Suspend Function

    61.5 Implementing the launchCoroutines Method

    61.6 Testing the App

    61.7 Summary

    62. An Overview of Android Services

    62.1 Intent Service

    62.2 Bound Service

    62.3 The Anatomy of a Service

    62.4 Controlling Destroyed Service Restart Options

    62.5 Declaring a Service in the Manifest File

    62.6 Starting a Service Running on System Startup

    62.7 Summary

    63. Android Local Bound Services – A Worked Example

    63.1 Understanding Bound Services

    63.2 Bound Service Interaction Options

    63.3 A Local Bound Service Example

    63.4 Adding a Bound Service to the Project

    63.5 Implementing the Binder

    63.6 Binding the Client to the Service

    63.7 Completing the Example

    63.8 Testing the Application

    63.9 Summary

    64. Android Remote Bound Services – A Worked Example

    64.1 Client to Remote Service Communication

    64.2 Creating the Example Application

    64.3 Designing the User Interface

    64.4 Implementing the Remote Bound Service

    64.5 Configuring a Remote Service in the Manifest File

    64.6 Launching and Binding to the Remote Service

    64.7 Sending a Message to the Remote Service

    64.8 Summary

    65. An Introduction to Kotlin Flow

    65.1 Understanding Flows

    65.2 Creating the Sample Project

    65.3 Adding the Kotlin Lifecycle Library

    65.4 Declaring a Flow

    65.5 Emitting Flow Data

    65.6 Collecting Flow Data

    65.7 Adding a Flow Buffer

    65.8 Transforming Data with Intermediaries

    65.9 Terminal Flow Operators

    65.10 Flow Flattening

    65.11 Combining Multiple Flows

    65.12 Hot and Cold Flows

    65.13 StateFlow

    65.14 SharedFlow

    65.15 Summary

    66. An Android SharedFlow Tutorial

    66.1 About the Project

    66.2 Creating the SharedFlowDemo Project

    66.3 Adding the Lifecycle Libraries

    66.4 Designing the User Interface Layout

    66.5 Adding the List Row Layout

    66.6 Adding the RecyclerView Adapter

    66.7 Adding the ViewModel

    66.8 Configuring the ViewModelProvider

    66.9 Collecting the Flow Values

    66.10 Testing the SharedFlowDemo App

    66.11 Handling Flows in the Background

    66.12 Summary

    67. An Overview of Android SQLite Databases

    67.1 Understanding Database Tables

    67.2 Introducing Database Schema

    67.3 Columns and Data Types

    67.4 Database Rows

    67.5 Introducing Primary Keys

    67.6 What is SQLite?

    67.7 Structured Query Language (SQL)

    67.8 Trying SQLite on an Android Virtual Device (AVD)

    67.9 Android SQLite Classes

    67.9.1 Cursor

    67.9.2 SQLiteDatabase

    67.9.3 SQLiteOpenHelper

    67.9.4 ContentValues

    67.10 The Android Room Persistence Library

    67.11 Summary

    68. An Android SQLite Database Tutorial

    68.1 About the Database Example

    68.2 Creating the SQLDemo Project

    68.3 Designing the User interface

    68.4 Creating the Data Model

    68.5 Implementing the Data Handler

    68.6 The Add Handler Method

    68.7 The Query Handler Method

    68.8 The Delete Handler Method

    68.9 Implementing the Activity Event Methods

    68.10 Testing the Application

    68.11 Summary

    69. Understanding Android Content Providers

    69.1 What is a Content Provider?

    69.2 The Content Provider

    69.2.1 onCreate()

    69.2.2 query()

    69.2.3 insert()

    69.2.4 update()

    69.2.5 delete()

    69.2.6 getType()

    69.3 The Content URI

    69.4 The Content Resolver

    69.5 The Manifest Element

    69.6 Summary

    70. An Android Content Provider Tutorial

    70.1 Copying the SQLDemo Project

    70.2 Adding the Content Provider Package

    70.3 Creating the Content Provider Class

    70.4 Constructing the Authority and Content URI

    70.5 Implementing URI Matching in the Content Provider

    70.6 Implementing the Content Provider onCreate() Method

    70.7 Implementing the Content Provider insert() Method

    70.8 Implementing the Content Provider query() Method

    70.9 Implementing the Content Provider update() Method

    70.10 Implementing the Content Provider delete() Method

    70.11 Declaring the Content Provider in the Manifest File

    70.12 Modifying the Database Handler

    70.13 Summary

    71. An Android Content Provider Client Tutorial

    71.1 Creating the SQLDemoClient Project

    71.2 Designing the User interface

    71.3 Accessing the Content Provider

    71.4 Adding the Query Permission

    71.5 Testing the Project

    71.6 Summary

    72. The Android Room Persistence Library

    72.1 Revisiting Modern App Architecture

    72.2 Key Elements of Room Database Persistence

    72.2.1 Repository

    72.2.2 Room Database

    72.2.3 Data Access Object (DAO)

    72.2.4 Entities

    72.2.5 SQLite Database

    72.3 Understanding Entities

    72.4 Data Access Objects

    72.5 The Room Database

    72.6 The Repository

    72.7 In-Memory Databases

    72.8 Database Inspector

    72.9 Summary

    73. An Android TableLayout and TableRow Tutorial

    73.1 The TableLayout and TableRow Layout Views

    73.2 Creating the Room Database Project

    73.3 Converting to a LinearLayout

    73.4 Adding the TableLayout to the User Interface

    73.5 Configuring the TableRows

    73.6 Adding the Button Bar to the Layout

    73.7 Adding the RecyclerView

    73.8 Adjusting the Layout Margins

    73.9 Summary

    74. An Android Room Database and Repository Tutorial

    74.1 About the RoomDemo Project

    74.2 Modifying the Build Configuration

    74.3 Building the Entity

    74.4 Creating the Data Access Object

    74.5 Adding the Room Database

    74.6 Adding the Repository

    74.7 Adding the ViewModel

    74.8 Creating the Product Item Layout

    74.9 Adding the RecyclerView Adapter

    74.10 Preparing the Main Activity

    74.11 Adding the Button Listeners

    74.12 Adding LiveData Observers

    74.13 Initializing the RecyclerView

    74.14 Testing the RoomDemo App

    74.15 Using the Database Inspector

    74.16 Summary

    75. Video Playback on Android using the VideoView and MediaController Classes

    75.1 Introducing the Android VideoView Class

    75.2 Introducing the Android MediaController Class

    75.3 Creating the Video Playback Example

    75.4 Designing the VideoPlayer Layout

    75.5 Downloading the Video File

    75.6 Configuring the VideoView

    75.7 Adding the MediaController to the Video View

    75.8 Setting up the onPreparedListener

    75.9 Summary

    76. Android Picture-in-Picture Mode

    76.1 Picture-in-Picture Features

    76.2 Enabling Picture-in-Picture Mode

    76.3 Configuring Picture-in-Picture Parameters

    76.4 Entering Picture-in-Picture Mode

    76.5 Detecting Picture-in-Picture Mode Changes

    76.6 Adding Picture-in-Picture Actions

    76.7 Summary

    77. An Android Picture-in-Picture Tutorial

    77.1 Adding Picture-in-Picture Support to the Manifest

    77.2 Adding a Picture-in-Picture Button

    77.3 Entering Picture-in-Picture Mode

    77.4 Detecting Picture-in-Picture Mode Changes

    77.5 Adding a Broadcast Receiver

    77.6 Adding the PiP Action

    77.7 Testing the Picture-in-Picture Action

    77.8 Summary

    78. Making Runtime Permission Requests in Android

    78.1 Understanding Normal and Dangerous Permissions

    78.2 Creating the Permissions Example Project

    78.3 Checking for a Permission

    78.4 Requesting Permission at Runtime

    78.5 Providing a Rationale for the Permission Request

    78.6 Testing the Permissions App

    78.7 Summary

    79. Android Audio Recording and Playback using MediaPlayer and MediaRecorder

    79.1 Playing Audio

    79.2 Recording Audio and Video using the MediaRecorder Class

    79.3 About the Example Project

    79.4 Creating the AudioApp Project

    79.5 Designing the User Interface

    79.6 Checking for Microphone Availability

    79.7 Initializing the Activity

    79.8 Implementing the recordAudio() Method

    79.9 Implementing the stopAudio() Method

    79.10 Implementing the playAudio() method

    79.11 Configuring and Requesting Permissions

    79.12 Testing the Application

    79.13 Summary

    80. An Android Notifications Tutorial

    80.1 An Overview of Notifications

    80.2 Creating the NotifyDemo Project

    80.3 Designing the User Interface

    80.4 Creating the Second Activity

    80.5 Creating a Notification Channel

    80.6 Requesting Notification Permission

    80.7 Creating and Issuing a Notification

    80.8 Launching an Activity from a Notification

    80.9 Adding Actions to a Notification

    80.10 Bundled Notifications

    80.11 Summary

    81. An Android Direct Reply Notification Tutorial

    81.1 Creating the DirectReply Project

    81.2 Designing the User Interface

    81.3 Requesting Notification Permission

    81.4 Creating the Notification Channel

    81.5 Building the RemoteInput Object

    81.6 Creating the PendingIntent

    81.7 Creating the Reply Action

    81.8 Receiving Direct Reply Input

    81.9 Updating the Notification

    81.10 Summary

    82. Printing with the Android Printing Framework

    82.1 The Android Printing Architecture

    82.2 The Print Service Plugins

    82.3 Google Cloud Print

    82.4 Printing to Google Drive

    82.5 Save as PDF

    82.6 Printing from Android Devices

    82.7 Options for Building Print Support into Android Apps

    82.7.1 Image Printing

    82.7.2 Creating and Printing HTML Content

    82.7.3 Printing a Web Page

    82.7.4 Printing a Custom Document

    82.8 Summary

    83. An Android HTML and Web Content Printing Example

    83.1 Creating the HTML Printing Example Application

    83.2 Printing Dynamic HTML Content

    83.3 Creating the Web Page Printing Example

    83.4 Removing the Floating Action Button

    83.5 Removing Navigation Features

    83.6 Designing the User Interface Layout

    83.7 Accessing the WebView from the Main Activity

    83.8 Loading the Web Page into the WebView

    83.9 Adding the Print Menu Option

    83.10 Summary

    84. A Guide to Android Custom Document Printing

    84.1 An Overview of Android Custom Document Printing

    84.1.1 Custom Print Adapters

    84.2 Preparing the Custom Document Printing Project

    84.3 Designing the UI

    84.4 Creating the Custom Print Adapter

    84.5 Implementing the onLayout() Callback Method

    84.6 Implementing the onWrite() Callback Method

    84.7 Checking a Page is in Range

    84.8 Drawing the Content on the Page Canvas

    84.9 Starting the Print Job

    84.10 Testing the Application

    84.11 Summary

    85. An Android Biometric Authentication Tutorial

    85.1 An Overview of Biometric Authentication

    85.2 Creating the Biometric Authentication Project

    85.3 Configuring Device Fingerprint Authentication

    85.4 Adding the Biometric Permission to the Manifest File

    85.5 Designing the User Interface

    85.6 Adding a Toast Convenience Method

    85.7 Checking the Security Settings

    85.8 Configuring the Authentication Callbacks

    85.9 Adding the CancellationSignal

    85.10 Starting the Biometric Prompt

    85.11 Testing the Project

    85.12 Summary

    86. Creating, Testing, and Uploading an Android App Bundle

    86.1 The Release Preparation Process

    86.2 Android App Bundles

    86.3 Register for a Google Play Developer Console Account

    86.4 Configuring the App in the Console

    86.5 Enabling Google Play App Signing

    86.6 Creating a Keystore File

    86.7 Creating the Android App Bundle

    86.8 Generating Test APK Files

    86.9 Uploading the App Bundle to the Google Play Developer Console

    86.10 Exploring the App Bundle

    86.11 Managing Testers

    86.12 Rolling the App Out for Testing

    86.13 Uploading New App Bundle Revisions

    86.14 Analyzing the App Bundle File

    86.15 Summary

    87. An Overview of Android In-App Billing

    87.1 Preparing a Project for In-App Purchasing

    87.2 Creating In-App Products and Subscriptions

    87.3 Billing Client Initialization

    87.4 Connecting to the Google Play Billing Library

    87.5 Querying Available Products

    87.6 Starting the Purchase Process

    87.7 Completing the Purchase

    87.8 Querying Previous Purchases

    87.9 Summary

    88. An Android In-App Purchasing Tutorial

    88.1 About the In-App Purchasing Example Project

    88.2 Creating the InAppPurchase Project

    88.3 Adding Libraries to the Project

    88.4 Designing the User Interface

    88.5 Adding the App to the Google Play Store

    88.6 Creating an In-App Product

    88.7 Enabling License Testers

    88.8 Initializing the Billing Client

    88.9 Querying the Product

    88.10 Launching the Purchase Flow

    88.11 Handling Purchase Updates

    88.12 Consuming the Product

    88.13 Restoring a Previous Purchase

    88.14 Testing the App

    88.15 Troubleshooting

    88.16 Summary

    89. Working with Material Design 3 Theming

    89.1 Material Design 2 vs. Material Design 3

    89.2 Understanding Material Design Theming

    89.3 Material Design 3 Theming

    89.4 Building a custom theme

    89.5 Summary

    90. A Material Design 3 Theming and Dynamic Color Tutorial

    90.1 Creating the ThemeDemo Project

    90.2 Designing the User Interface

    90.3 Building a new theme

    90.4 Adding the Theme to the Project

    90.5 Enabling Dynamic Color Support

    90.6 Summary

    91. An Overview of Gradle in Android Studio

    91.1 An Overview of Gradle

    91.2 Gradle and Android Studio

    91.2.1 Sensible Defaults

    91.2.2 Dependencies

    91.2.3 Build Variants

    91.2.4 Manifest Entries

    91.2.5 APK Signing

    91.2.6 ProGuard Support

    91.3 The Property and Settings Gradle Build File

    91.4 The Top-level Gradle Build File

    91.5 Module Level Gradle Build Files

    91.6 Configuring Signing Settings in the Build File

    91.7 Running Gradle Tasks from the Command Line

    91.8 Summary

    Index

    1. Introduction

    This book, fully updated for Android Studio Meerkat and the new UI, teaches you how to develop Android-based applications using Kotlin.

    Beginning with the basics, the book outlines how to set up an Android development and testing environment, followed by an introduction to programming in Kotlin, including data types, control flow, functions, lambdas, and object-oriented programming. Asynchronous programming using Kotlin coroutines and flow is also covered in detail.

    Chapters also cover the Android Architecture Components, including view models, lifecycle management, Room database access, content providers, the Database Inspector, app navigation, live data, and data binding.

    More advanced topics, such as intents, are also covered, such as touchscreen handling, gesture recognition, and the recording and playback of audio. This book edition also covers printing, transitions, and foldable device support.

    The concepts of material design are also covered in detail, including the use of floating action buttons, Snackbars, tabbed interfaces, card views, navigation drawers, and collapsing toolbars.

    Other key features of Android Studio and Android are also covered in detail, including the Layout Editor, the ConstraintLayout and ConstraintSet classes, view binding, constraint chains, barriers, and direct reply notifications.

    Chapters also cover advanced features of Android Studio, such as Gradle build configuration, in-app billing, and submitting apps to the Google Play Developer Console.

    Assuming you already have some programming experience, are ready to download Android Studio and the Android SDK, have access to a Windows, Mac, or Linux system, and have ideas for some apps to develop, you are ready to get started.

    1.1 Downloading the Code Samples

    The source code and Android Studio project files for the examples contained in this book are available for download at:

    https://www.payloadbooks.com/product/meerkatkotlin/

    The steps to load a project from the code samples into Android Studio are as follows:

    1. From the Welcome to Android Studio dialog, click on the Open button option.

    2. In the project selection dialog, navigate to and select the folder containing the project to be imported and click on OK.

    1.2 Feedback

    We want you to be satisfied with your purchase of this book. If you find any errors in the book, or have any comments, questions or concerns please contact us at [email protected].

    1.3 Errata

    While we make every effort to ensure the accuracy of the content of this book, it is inevitable that a book covering a subject area of this size and complexity may include some errors and oversights. Any known issues with the book will be outlined, together with solutions, at the following URL:

    https://www.payloadbooks.com/meerkatkotlin

    If you find an error not listed in the errata, please let us know by emailing our technical support team at [email protected]. They are there to help you and will work to resolve any problems you may encounter.

    2. Setting up an Android Studio Development Environment

    Before any work can begin on developing an Android application, the first step is to configure a computer system to act as the development platform. This involves several steps consisting of installing the Android Studio Integrated Development Environment (IDE), including the Android Software Development Kit (SDK), the Kotlin plug-in and the OpenJDK Java development environment.

    This chapter will cover the steps necessary to install the requisite components for Android application development on Windows, macOS, and Linux-based systems.

    2.1 System requirements

    Android application development may be performed on any of the following system types:

    •Windows 10 or 11 64-bit

    •macOS 12 or later running on Intel or Apple silicon

    •Chrome OS device with Intel i5 or higher

    •Linux systems with version 2.31 or later of the GNU C Library (glibc)

    •Minimum of 8 GB of RAM (16 GB recommended)

    •Approximately 8 GB of available disk space

    •1280 x 800 minimum screen resolution

    2.2 Downloading the Android Studio package

    Most of the work involved in developing applications for Android will be performed using the Android Studio environment. The content and examples in this book were created based on Android Studio Meerkat 2024.3.1 using the Android API 35 SDK (VanillaIceCream), which, at the time of writing, are the latest stable releases.

    Android Studio is, however, subject to frequent updates, so a newer version may have been released since this book was published.

    The latest release of Android Studio may be downloaded from the primary download page, which can be found at the following URL:

    https://developer.android.com/studio/index.html

    If this page provides instructions for downloading a newer version of Android Studio, there may be differences between this book and the software. A web search for Android Studio Meerkat should provide the option to download the older version if these differences become a problem. Alternatively, visit the following web page to find Android Studio Meerkat 2024.3.1 in the archives:

    https://developer.android.com/studio/archive

    2.3 Installing Android Studio

    Once downloaded, the exact steps to install Android Studio differ depending on the operating system on which the installation is performed.

    2.3.1 Installation on Windows

    Locate the downloaded Android Studio installation executable file (named android-studio--windows.exe) in a Windows Explorer window and double-click on it to start the installation process, clicking the Yes button in the User Account Control dialog if it appears.

    Once the Android Studio setup wizard appears, work through the various screens to configure the installation to meet your requirements in terms of the file system location into which Android Studio should be installed and whether or not it should be made available to other system users. When prompted to select the components to install, ensure that the Android Studio and Android Virtual Device options are all selected.

    Although there are no strict rules on where Android Studio should be installed on the system, the remainder of this book will assume that the installation was performed into C:\Program Files\Android\Android Studio and that the Android SDK packages have been installed into the user’s AppData\Local\Android\sdk sub-folder. Once the options have been configured, click the Install button to begin the installation process.

    On versions of Windows with a Start menu, the newly installed Android Studio can be launched from the entry added to that menu during the installation. The executable may be pinned to the taskbar for easy access by navigating to the Android Studio\bin directory, right-clicking on the studio64 executable, and selecting the Pin to Taskbar menu option (on Windows 11, this option can be found by selecting Show more options from the menu).

    2.3.2 Installation on macOS

    Android Studio for macOS is downloaded as a disk image (.dmg) file. Once the android-studio--mac.dmg file has been downloaded, locate it in a Finder window and double-click on it to open it, as shown in Figure 2-1:

    Figure 2-1

    To install the package, drag the Android Studio icon and drop it onto the Applications folder. The Android Studio package will then be installed into the Applications folder of the system, a process that will typically take a few seconds to complete.

    To launch Android Studio, locate the executable in the Applications folder using a Finder window and double-click on it.

    For future, easier access to the tool, drag the Android Studio icon from the Finder window and drop it onto the dock.

    2.3.3 Installation on Linux

    Having downloaded the Linux Android Studio package, open a terminal window, change directory to the location where Android Studio is to be installed, and execute the following command:

    tar xvfz //android-studio--linux.tar.gz

    Note that the Android Studio bundle will be installed into a subdirectory named android-studio. Therefore, assuming that the above command was executed in /home/demo, the software packages will be unpacked into /home/demo/android-studio.

    To launch Android Studio, open a terminal window, change directory to the android-studio/bin sub-directory, and execute the following command:

    ./studio.sh

    2.4 The Android Studio setup wizard

    If you have previously installed an earlier version of Android Studio, the first time this new version is launched, a dialog may appear providing the option to import settings from a previous Android Studio version. If you have settings from a previous version and would like to import them into the latest installation, select the appropriate option and location. Alternatively, indicate that you do not need to import any previous settings and click the OK button to proceed.

    If you are installing Android Studio for the first time, the initial dialog that appears once the setup process starts may resemble that shown in Figure 2-2 below:

    Figure 2-2

    If this dialog appears, click the Next button to display the Install Type screen (Figure 2-3). On this screen, select the Standard installation option before clicking Next.

    Figure 2-3

    Click Next and review the options in the Verify Settings screen before proceeding to the License Agreement screen. Enable the Accept checkbox and click the Finish button to start the installation.

    After these initial setup steps have been taken, click the Finish button to display the Welcome to Android Studio screen using your chosen UI theme:

    Figure 2-4

    2.5 Installing additional Android SDK packages

    The steps performed so far have installed the Android Studio IDE and the current set of default Android SDK packages. Before proceeding, it is worth taking some time to verify which packages are installed and to install any missing or updated packages.

    This task can be performed by clicking on the More Actions link within the welcome dialog and selecting the SDK Manager option from the drop-down menu. Once invoked, the Android SDK screen of the Settings dialog will appear as shown in Figure 2-5:

    Figure 2-5

    Google pairs each release of Android Studio with a maximum supported Application Programming Interface (API) level of the Android SDK. In the case of Android Studio Meerkat, this is Android VanillaIceCream (API Level 35). This information can be confirmed using the following link:

    https://developer.android.com/studio/releases#api-level-support

    Immediately after installing Android Studio for the first time, it is likely that only the latest supported version of the Android SDK has been installed. To install older versions of the Android SDK, select the checkboxes corresponding to the versions and click the Apply button. The rest of this book assumes that the Android VanillaIceCream (API Level 35) SDK is installed.

    Most of the examples in this book will support older versions of Android as far back as Android 8.0 (Oreo). This ensures that the apps run on a wide range of Android devices. Within the list of SDK versions, enable the checkbox next to Android 8.0 (Oreo) and click the Apply button. Click the OK button to install the SDK in the resulting confirmation dialog. Subsequent dialogs will seek the acceptance of licenses and terms before performing the installation. Click Finish once the installation is complete.

    It is also possible that updates will be listed as being available for the latest SDK. To access detailed information about the packages that are ready to be updated, enable the Show Package Details option located in the lower right-hand corner of the screen. This will display information similar to that shown in Figure 2-6:

    Figure 2-6

    The above figure highlights the availability of an update. To install the updates, enable the checkbox to the left of the item name and click the Apply button.

    In addition to the Android SDK packages, several tools are also installed for building Android applications. To view the currently installed packages and check for updates, remain within the SDK settings screen and select the SDK Tools tab as shown in Figure 2-7:

    Figure 2-7

    Within the Android SDK Tools screen, make sure that the following packages are listed as Installed in the Status column:

    •Android SDK Build-tools

    •Android Emulator

    •Android SDK Platform-tools

    •Google Play Services

    •Intel x86 Emulator Accelerator (HAXM installer)*

    •Google USB Driver (Windows only)

    •Layout Inspector image server for API 31-36

    *Note that the Intel x86 Emulator Accelerator (HAXM installer) requires an Intel processor with VT-x support enabled. It cannot be installed on Apple silicon-based Macs or AMD-based PCs.

    If any of the above packages are listed as Not Installed or requiring an update, select the checkboxes next to those packages and click the Apply button to initiate the installation process. If the HAXM emulator settings dialog appears, select the recommended memory allocation:

    Figure 2-8

    Once the installation is complete, review the package list and ensure that the selected packages are listed as Installed in the Status column. If any are listed as Not installed, make sure they are selected and click the Apply button again.

    2.6 Installing the Android SDK Command-line Tools

    Android Studio includes tools that allow some tasks to be performed from your operating system command line. To install these tools on your system, open the SDK Manager, select the SDK Tools tab, and locate the Android SDK Command-line Tools (latest) package as shown in Figure 2-9:

    Figure 2-9

    If the command-line tools package is not already installed, enable it and click Apply, followed by OK to complete the installation. When the installation completes, click Finish and close the SDK Manager dialog.

    For the operating system on which you are developing to be able to find these tools, it will be necessary to add them to the system’s PATH environment variable.

    Regardless of your operating system, you will need to configure the PATH environment variable to include the following paths (where represents the file system location into which you installed the Android SDK):

    /sdk/cmdline-tools/latest/bin

    /sdk/platform-tools

    You can identify the location of the SDK on your system by launching the SDK Manager and referring to the Android SDK Location: field located at the top of the settings panel, as highlighted in Figure 2-10:

    Figure 2-10

    Once the location of the SDK has been identified, the steps to add this to the PATH variable are operating system dependent:

    2.6.1 Windows 8.1

    1. On the start screen, move the mouse to the bottom right-hand corner of the screen and select Search from the resulting menu. In the search box, enter Control Panel. When the Control Panel icon appears in the results area, click on it to launch the tool on the desktop.

    2. Within the Control Panel, use the Category menu to change the display to Large Icons. From the list of icons, select the one labeled System.

    3. In the Environment Variables dialog, locate the Path variable in the System variables list, select it, and click the Edit… button. Using the New button in the edit dialog, add two new entries to the path. For example, assuming the Android SDK was installed into C:\Users\demo\AppData\Local\Android\Sdk, the following entries would need to be added:

    C:\Users\demo\AppData\Local\Android\Sdk\cmdline-tools\latest\bin

    C:\Users\demo\AppData\Local\Android\Sdk\platform-tools

    4. Click OK in each dialog box and close the system properties control panel.

    Open a command prompt window by pressing Windows + R on the keyboard and entering cmd into the Run dialog. Within the Command Prompt window, enter:

    echo %Path%

    The returned path variable value should include the paths to the Android SDK platform tools folders. Verify that the platform-tools value is correct by attempting to run the adb tool as follows:

    adb

    The tool should output a list of command-line options when executed.

    Similarly, check the tools path setting by attempting to run the AVD Manager command-line tool (don’t worry if the avdmanager tool reports a problem with Java - this will be addressed later):

    avdmanager

    If a message similar to the following message appears for one or both of the commands, it is most likely that an incorrect path was appended to the Path environment variable:

    'adb' is not recognized as an internal or external command,

    operable program or batch file.

    2.6.2 Windows 10

    Right-click on the Start menu, select Settings from the resulting menu and enter Edit the system environment variables into the Find a setting text field. In the System Properties dialog, click the Environment Variables... button. Follow the steps outlined for Windows 8.1 starting from step 3.

    2.6.3 Windows 11

    Right-click on the Start icon located in the taskbar and select Settings from the resulting menu. When the Settings dialog appears, scroll down the list of categories and select the About option. In the About screen, select Advanced system settings from the Related links section. When the System Properties window appears, click the Environment Variables... button. Follow the steps outlined for Windows 8.1 starting from step 3.

    2.6.4 Linux

    This configuration can be achieved on Linux by adding a command to the .bashrc file in your home directory (specifics may differ depending on the particular Linux distribution in use). Assuming that the Android SDK bundle package was installed into /home/demo/Android/sdk, the export line in the .bashrc file would read as follows:

    export PATH=/home/demo/Android/sdk/platform-tools:/home/demo/Android/sdk/cmdline-tools/latest/bin:/home/demo/android-studio/bin:$PATH

    Note also that the above command adds the android-studio/bin directory to the PATH variable. This will enable the studio.sh script to be executed regardless of the current directory within a terminal window.

    2.6.5 macOS

    Several techniques may be employed to modify the $PATH environment variable on macOS. Arguably the cleanest method is to add a new file in the /etc/paths.d directory containing the paths to be added to $PATH. Assuming an Android SDK installation location of /Users/demo/Library/Android/sdk, the path may be configured by creating a new file named android-sdk in the /etc/paths.d directory containing the following lines:

    /Users/demo/Library/Android/sdk/cmdline-tools/latest/bin

    /Users/demo/Library/Android/sdk/platform-tools

    Note that since this is a system directory, it will be necessary to use the sudo command when creating the file. For example:

    sudo vi /etc/paths.d/android-sdk

    2.7 Android Studio memory management

    Android Studio is a large and complex software application with many background processes. Although Android Studio has been criticized in the past for providing less than optimal performance, Google has made significant performance improvements in recent releases and continues to do so with each new version. These improvements include allowing the user to configure the amount of memory used by both the Android Studio IDE and the background processes used to build and run apps. This allows the software to take advantage of systems with larger amounts of RAM.

    If you are running Android Studio on a system with sufficient unused RAM to increase these values (this feature is only available on 64-bit systems with 5GB or more of RAM) and find that Android Studio performance appears to be degraded, it may be worth experimenting with these memory settings. Android Studio may also notify you that performance can be increased via a dialog similar to the one shown below:

    Figure 2-11

    To view and modify the current memory configuration, select the File -> Settings... main menu option (Android Studio -> Settings... on macOS) and, in the resulting dialog, select Appearance & Behavior followed by the Memory Settings option listed under System Settings in the left-hand navigation panel, as illustrated in Figure 2-12 below:

    Figure 2-12

    When changing the memory allocation, be sure not to allocate more memory than necessary or than your system can spare without slowing down other processes.

    The IDE heap size setting adjusts the memory allocated to Android Studio and applies regardless of the currently loaded project. On the other hand, when a project is built and run from within Android Studio, several background processes (referred to as daemons) perform the task of compiling and running the app. When compiling and running large and complex projects, build time could be improved by adjusting the

    daemon heap settings. Unlike the IDE heap settings, these daemon settings apply only to the current project and can only be accessed when a project is open in Android Studio. To display the SDK Manager from within an open project, select the Tools -> SDK Manager... menu option from the main menu.

    2.8 Updating Android Studio and the SDK

    From time to time, new versions of Android Studio and the Android SDK are released. New versions of the SDK are installed using the Android SDK Manager. Android Studio will typically notify you when an update is ready to be installed.

    To manually check for Android Studio updates, use the Help -> Check for Updates... menu option from the Android Studio main window (Android Studio -> Check for Updates... on macOS).

    2.9 Summary

    Before beginning the development of Android-based applications, the first step is to set up a suitable development environment. This consists of the Android SDKs and Android Studio IDE (which also includes the OpenJDK development environment). This chapter covers the steps necessary to install these packages on Windows, macOS, and Linux.

    3. Creating an Example Android App in Android Studio

    The preceding chapters of this book have explained how to configure an environment suitable for developing Android applications using the Android Studio IDE. Before moving on to slightly more advanced topics, now is a good time to validate that all required development packages are installed and functioning correctly. The best way to achieve this goal is to create an Android application and compile and run it. This chapter will cover creating an Android application project using Android Studio. Once the project has been created, a later chapter will explore using the Android emulator environment to perform a test run of the application.

    3.1 About the Project

    The project created in this chapter takes the form of a rudimentary currency conversion calculator (so simple, in fact, that it only converts from dollars to euros and does so using an estimated conversion rate). The project will also use one of the most basic Android Studio project templates. This simplicity allows us to introduce some key aspects of Android app development without overwhelming the beginner by introducing too many concepts, such as the recommended app architecture and Android architecture components, at once. When following the tutorial in this chapter, rest assured that the techniques and code used in this initial example project will be covered in much greater detail later.

    3.2 Creating a New Android Project

    The first step in the application development process is to create a new project within the Android Studio environment. Begin, therefore, by launching Android Studio so that the Welcome to Android Studio screen appears as illustrated in Figure 3-1:

    Figure 3-1

    Once this window appears, Android Studio is ready for a new project to be created. To create the new project, click on the New Project option to display the first screen of the New Project wizard.

    3.3 Creating an Activity

    The next step is to define the type of initial activity to be created for the application. Options are available to create projects for Phone and Tablet, Wear OS, Television, or Automotive. A range of different activity types is available when developing Android applications, many of which will be covered extensively in later chapters. For this example, however, select the Phone and Tablet option from the Templates panel, followed by the option to create an Empty Views Activity. The Empty Views Activity option creates a template user interface consisting of a single TextView object.

    Figure 3-2

    With the Empty Views Activity option selected, click Next to continue with the project configuration.

    3.4 Defining the Project and SDK Settings

    In the project configuration window (Figure 3-3), set the Name field to AndroidSample. The application name is the name by which the application will be referenced and identified within Android Studio and is also the name that would be used if the completed application were to go on sale in the Google Play store.

    The Package name uniquely identifies the application within the Android application ecosystem. Although this can be set to any string that uniquely identifies your app, it is traditionally based on the reversed URL of your domain name followed by the application’s name. For example, if your domain is www.mycompany.com, and the application has been named AndroidSample, then the package name might be specified as follows:

    com.mycompany.androidsample

    If you do not have a domain name, you can enter any other string into the Company Domain field, or you may use example.com for testing, though this will need to be changed before an application can be published:

    com.example.androidsample

    The Save location setting will default to a location in the folder named AndroidStudioProjects located in your home directory and may be changed by clicking on the folder icon to the right of the text field containing the current path setting.

    Set the minimum SDK setting to API 26 (Oreo; Android 8.0). This minimum SDK will be used in most projects created in this book unless a necessary feature is only available in a more recent version. The objective here is to build an app using the latest Android SDK while retaining compatibility with devices running older versions of Android (in this case, as far back as Android 8.0). The text beneath the Minimum SDK setting will outline the percentage of Android devices currently in use on which the app will run. Click on the Help me choose button to see a full breakdown of the various Android versions still in use:

    Figure 3-3

    Finally, change the Language menu to Kotlin and select Kotlin DSL (build.gradle.kts) as the build configuration language before clicking Finish to create the project.

    3.5 Modifying the Example Application

    Once the project has been created, the main window will appear containing our AndroidSample project, as illustrated in Figure 3-4 below:

    Figure 3-4

    The newly created project and references to associated files are listed in the Project tool window on the left side of the main project window. The Project tool window has several modes in which information can be displayed. By default, this panel should be in Android mode. This setting is controlled by the menu at the top of the panel as highlighted in Figure 3-5. If the panel is not currently in Android mode, use the menu to switch mode:

    Figure 3-5

    3.6 Modifying the User Interface

    The user interface design for our activity is stored in a file named activity_main.xml which, in turn, is located under app -> res -> layout in the Project tool window file hierarchy. Once located in the Project tool window, double-click on the file to load it into the user interface Layout Editor tool, which will appear in the center panel of the Android Studio main window:

    Figure 3-6

    In the toolbar across the top of the Layout Editor window is a menu (currently set to Pixel in the above figure) which is reflected in the visual representation of the device within the Layout Editor panel. A range of other device options are available by clicking on this menu.

    Use the System UI Mode button ( ) to turn Night mode on and off for the device screen layout. To change the orientation of the device representation between landscape and portrait, use the drop-down menu showing the icon.

    As we can see in the device screen, the content layout already includes a label that displays a Hello World! message. Running down the left-hand side of the panel is a palette containing different categories of user interface components that may be used to construct a user interface, such as buttons, labels, and text fields. However, it should be noted that not all user interface components are visible to the user. One such category consists of layouts. Android supports a variety of layouts that provide different levels of control over how visual user interface components are positioned and managed on the screen. Though it is difficult to tell from looking at the visual representation of the user interface, the current design has been created using a ConstraintLayout. This can be confirmed by reviewing the information in the Component Tree panel, which, by default, is located in the lower left-hand corner of the Layout Editor panel and is shown in Figure 3-7:

    Figure 3-7

    As we can see from the component tree hierarchy, the user interface layout consists of a ConstraintLayout parent called main and a TextView child object.

    Before proceeding, check that the Layout Editor’s Autoconnect mode is enabled. This means that as components are added to the layout, the Layout Editor will automatically add constraints to ensure the components are correctly positioned for different screen sizes and

    Enjoying the preview?
    Page 1 of 1