
How to Build Android Applications with Kotlin
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
- Leverage the latest libraries to accelerate your Android development
- Overcome development challenges with tips and tricks from experienced Android professionals
- Get With Your Book: PDF Copy, AI Assistant, and Next-Gen Reader Free
Book DescriptionWritten by four veteran developers with 60+ years of collective experience, this updated third edition will jumpstart your Android development journey, focusing on Kotlin libraries and Jetpack Compose, Google's powerful declarative UI framework. You'll learn the fundamentals of app development, enabling you to use Android Studio, as well as get to grips with Jetpack Compose to create your first screens, build apps to run them on virtual devices through guided exercises, and implement Jetpack Compose's layout groups to make the most of lists, images, and maps. The book has been updated with Kotlin's powerful networking and coroutines libraries to help you fetch data in the background from a web service and manage displaying the data using Kotlin flows. You'll learn about testing, creating clean architecture, and persisting data, as well as exploring the dependency injection pattern and learning how to publish your apps on the Google Play Store. You'll also work on realistic projects split up into bite-size exercises and activities, along with building apps to create quizzes, read news articles, check weather reports, store recipes, retrieve movie information, and remind you where you parked your car. By the end of this book, you'll have gained the skills and confidence to build your own creative Android apps using Kotlin.What you will learn - Create maintainable and scalable apps using Kotlin
- Grasp Android asynchronous programming with coroutines and the Flow API
- Simplify app development with Google architecture components
- Apply MVVM and Repository architecture patterns to standardize retrieving and displaying data from outside sources
- Increase app stability and robustness with unit and integration tests
- Use standard libraries for dependency injection, networking, data parsing, and persistence
- Publish your app on the Google Play Store
Who this book is forThis book is for beginners as well as intermediate-level developers with no prior experience in Android app development. Basic knowledge of the Kotlin programming language or experience in a similar programming language, along with a willingness to brush up on Kotlin is required.
All prices
More details
Content
- Cover
- Title Page
- Copyright Page
- Foreword
- Contributors
- Table of Contents
- Preface
- Part 1: Android Foundation
- Chapter 1: Creating Your First App
- Getting the most out of this book - get to know your free benefits
- Next-gen reader
- Interactive AI assistant (beta)
- DRM-free PDF or ePub version
- Technical requirements
- Creating an Android project with Android Studio
- Exercise 1.01 - Creating an Android Studio project for your app
- Setting up a virtual device and running your app
- Exercise 1.02 - Setting up a virtual device and running your app on it
- The Android manifest file
- Exercise 1.03 - Configuring the Android manifest internet permission
- Using Gradle to build, configure, and manage app dependencies
- The project-level build.gradle.kts file
- The app-level build.gradle.kts file
- Exercise 1.04 - Exploring how Material Design in Jetpack Compose is used to theme an app
- Android application structure
- Exercise 1.05 - Building a Jetpack Compose UI to display a bespoke greeting to the user
- Activity 1.01 - Producing an app to create RGB colors
- Summary
- Chapter 2: Building User Screen Flows
- Technical requirements
- The activity lifecycle
- Exercise 2.01 - logging activity callbacks
- Saving and restoring the activity state
- Exercise 2.02 - saving and restoring the state
- Exercise 2.03 - saving and restoring state in Compose
- Activity interaction with intents
- Exercise 2.04 - an introduction to intents
- Exercise 2.05 - retrieving a result from an activity
- Intents, tasks, and launch modes
- Exercise 2.06 - setting the launch mode of an activity
- Activity 2.01 and/or Activity 2.02 - creating a login form
- Summary
- Chapter 3: Developing the UI with Jetpack Compose
- Technical requirements
- Transitioning from XML layouts to Jetpack Compose
- Exercise 3.01 - Creating a counter app with legacy views
- Exercise 3.02 - Creating an Android app with Compose
- Essential composable functions
- Text
- Button
- Icon
- Image
- Text input fields
- Checkbox
- Switch
- Slider
- RadioButton
- Progress indicators
- AlertDialog
- Exercise 3.03 - Creating a Settings screen
- Jetpack Compose layout groups
- Box
- Surface
- Card
- Column
- Row
- Exercise 3.04 - Creating a Profile page
- Activity 3.01 - Creating a business metrics dashboard
- Summary
- Chapter 4: Building App Navigation
- Technical requirements
- Creating a screen structure with a Scaffold composable and slots
- Building a navigation graph
- Exercise 4.1 - Building simple navigation
- Implementing a navigation drawer
- Exercise 4.2 - Creating an app with a navigation drawer
- Adding bottom navigation
- Exercise 4.3 - Adding bottom navigation to your app
- Introducing tabbed navigation
- Exercise 4.4 - Using tabs for app navigation
- Activity 4.1 - Building primary and secondary app navigation
- Summary
- Part 2: App Components
- Chapter 5: Essential Libraries - Ktor, Kotlin Serialization, and Coil
- Technical requirements
- Introducing REST, API, JSON, and XML
- REST and APIs
- JSON
- XML
- Processing JSON payloads
- Fetching data from a network endpoint
- Setting up Ktor and internet permissions
- Making API requests with Ktor and displaying data
- Exercise 5.1 - reading data from an API
- Parsing a JSON response
- Configuring Kotlin Serialization with Ktor
- Defining data models for JSON mapping
- Exercise 5.2 - extracting the image URL from the API response
- Loading images from a remote URL
- Exercise 5.3 - loading the image from the obtained URL
- Activity 5.1 - displaying the current weather
- Summary
- Chapter 6: Building Lists with Jetpack Compose
- Technical requirements
- Adding a lazy list to our layout
- Exercise 6.01 - Adding an empty LazyColumn to your main activity
- Populating a LazyColumn composable
- Exercise 6.02 - Populating your LazyColumn composable
- Responding to clicks in LazyColumn composables
- Exercise 6.03 - Responding to clicks
- Supporting different item types
- Exercise 6.04 - Adding titles to lazy lists
- Swiping to remove items
- Exercise 6.05 - Adding swipe-to-delete functionality
- Adding items interactively
- Exercise 6.06 - Implementing an Add Cat button
- Activity 6.01 - Managing a list of Items
- Summary
- Further reading
- Chapter 7: Android Permissions and Google Maps
- Technical requirements
- Requesting permission from the user
- Exercise 7.01 - requesting the location permission
- Showing a map of the user's location
- Exercise 7.02 - obtaining the user's current location
- Map clicks and custom markers
- Exercise 7.03 - adding a custom marker where the map was clicked
- Activity 7.01 - creating an app to find the location of a parked car
- Summary
- Chapter 8: Services, WorkManager, and Notifications
- Technical requirements
- Starting a background task using WorkManager
- Exercise 8.01 - Executing background work with the WorkManager class
- Background operations noticeable to the user - using foreground workers
- Exercise 8.02 - Tracking your SCA with a foreground worker
- Canceling or updating ongoing work
- Exercise 8.03 - Aborting SCA deployment by canceling a worker
- Activity 8.01 - A reminder to drink water
- Summary
- Part 3: Code Structure
- Chapter 9: Testing with JUnit, Mockito, MockK, and Compose
- Technical requirements
- Understanding the types of testing
- Writing a simple JUnit test
- Creating and running basic unit tests
- Handling edge cases and improving test reliability
- Using Android Studio to run tests
- Mocking objects
- Using MockK
- Exercise 9.01 - Testing the sum of numbers
- Writing integration tests
- Robolectric
- Jetpack ComposeTestRule library
- Exercise 9.02 - Double integration
- Running UI tests
- Exercise 9.03 - Dealing with random events
- Applying TDD
- Exercise 9.04 - Using TDD to calculate the sum of numbers
- Activity 9.01 - Developing with TDD
- Summary
- Chapter 10: Coroutines and Flow
- Technical requirements
- Using Coroutines on Android
- Coroutine builders
- Coroutine scope
- Creating coroutines
- Coroutine dispatchers
- Coroutine contexts
- Coroutine Job elements
- Exercise 10.01 - using Coroutines in an Android app
- Using Flow on Android
- Collecting flows on Android
- Creating flows with flow builders
- Using operators with flows
- Exercise 10.02 - using Flow in an Android application
- Activity 10.01 - creating a TV guide app
- Summary
- Chapter 11: Android Architecture Components
- Technical requirements
- Understanding Android components' background
- Exploring ViewModel
- Exercise 11.01 - Compose and ViewModel components
- Combining ViewModel with data streams
- LiveData
- Coroutines and flows
- Exercise 11.02 - Compose, ViewModel components, and flows
- Saving instance states inside ViewModels
- Persisting data with Room
- Entities
- DAO
- Setting up the database
- Third-party frameworks
- Exercise 11.03 - making a little room
- Activity 11.01 - shopping notes app
- Summary
- Chapter 12: Persisting Data
- Technical requirements
- Using SharedPreferences and DataStore
- SharedPreferences
- Exercise 12.01 - wrapping SharedPreferences
- DataStore
- Exercise 12.02 - Preferences DataStore
- Saving data into files
- Internal storage
- External storage
- FileProvider
- The Storage Access Framework
- Asset files
- Exercise 12.03 - copying files
- Understanding scoped storage
- Camera and media storage
- Exercise 12.04 - taking photos
- Activity 12.01 - managing multiple persistence options
- Summary
- Chapter 13: Dependency Injection with Dagger, Hilt, and Koin
- Technical requirements
- Handling manual DI
- Exercise 13.01 - manual injection
- Using Dagger 2
- Consumers
- Providers
- Connectors
- Qualifiers
- Scopes
- Subcomponents
- Exercise 13.02 - Dagger injection
- Switching to Hilt
- Exercise 13.03 - Hilt injection
- Using Koin
- Exercise 13.04 - Koin injection
- Activity 13.01 - injected repositories
- Summary
- Part 4: Polishing and Publishing an App
- Chapter 14: Architecture Patterns
- Technical requirements
- Getting started with MVVM
- Implementing the Repository pattern
- Exercise 14.1 - using Repository with Room in an Android project
- Activity 14.1 - revisiting the TV Guide app
- Summary
- Chapter 15: Advanced Jetpack Compose
- Technical requirements
- Using CompositionLocal
- Exercise 15.01 - adding CompositionLocal in an app
- Using side-effects with Jetpack Compose
- LaunchedEffect
- DisposableEffect
- SideEffect
- Exercise 15.02 - adding side-effects in an app
- Creating animations using Jetpack Compose
- Animating a single value
- Animating the appearance or disappearance of elements
- Animating multiple values
- Animating size changes of elements
- Animating changes between composables
- Animating values indefinitely
- Other compose animations
- Customizing animations
- Debugging animations
- Exercise 15.03 - adding animations with Jetpack Compose
- Activity 15.01 - adding Animations to the TV Guide app
- Summary
- Chapter 16: Launching Your App on Google Play
- Preparing your apps for release
- Versioning apps
- Creating a keystore
- Exercise 16.01 - creating a keystore in Android Studio
- Storing the keystore and passwords
- Signing your apps for release
- Android App Bundle
- Exercise 16.02 - creating a signed app bundle
- App signing by Google Play
- Creating a developer account
- Uploading an app to Google Play
- Creating a store listing
- App details
- Graphic assets
- Preparing the release
- App bundle
- Rolling out a release
- Managing app releases
- Release tracks
- The feedback channel and opt-in link
- Internal testing
- Closed testing
- Open testing
- Staged rollouts
- Managed publishing
- Activity 16.01 - publishing an app
- Summary
- Chapter 17: Unlock Your Book's Exclusive Benefits
- How to unlock these benefits in three easy steps
- Step 1
- Step 2
- Step 3
- Need help?
- About Packt
- Other Books You May Enjoy
- Index
1
Creating Your First App
This chapter is an introduction to Android, where you will set up the Android Studio environment and focus on the fundamentals of Android development.
You will cover creating an Android project with Android Studio. Then, you will set up a virtual device and run your app on it. You will explore the Android manifest file, which details all the Android app components, features, and permissions model. You will learn how to use the Gradle build system and analyze the Android application structure. You will start developing user interfaces (UIs) with the Android UI toolkit, Jetpack Compose.
By the end of this chapter, you will have gained the knowledge required to create an Android app from scratch and install it on a virtual Android device. You will be able to analyze and understand the importance of the AndroidManifest.xml file. You will know how an app project is structured in Android Studio and use the Gradle build tool to configure and build your app and manage library dependencies. Finally, you will be able to start implementing UI elements using Jetpack Compose with Material Design.
We will cover the following topics in the chapter:
- Creating an Android project with Android Studio
- Setting up a virtual device and running your app
- The Android manifest file
- Using Gradle to build, configure, and manage app dependencies
- Android application structure
Getting the most out of this book - get to know your free benefits
Unlock exclusive free benefits that come with your purchase, thoughtfully crafted to supercharge your learning journey and help you learn without limits.
Here's a quick overview of what you get with this book:
Next-gen reader
Figure 1.1: Illustration of the next-gen Packt Reader's features
Our web-based reader, designed to help you learn effectively, comes with the following features:
Multi-device progress sync: Learn from any device with seamless progress sync.
Highlighting and notetaking: Turn your reading into lasting knowledge.
Bookmarking: Revisit your most important learnings anytime.
Dark mode: Focus with minimal eye strain by switching to dark or sepia mode.
Interactive AI assistant (beta)
Figure 1.2: Illustration of Packt's AI assistant
Our interactive AI assistant has been trained on the content of this book, to maximize your learning experience. It comes with the following features:
Summarize it: Summarize key sections or an entire chapter.
AI code explainers: In the next-gen Packt Reader, click the Explain button above each code block for AI-powered code explanations.
Note: The AI assistant is part of next-gen Packt Reader and is still in beta.
DRM-free PDF or ePub version
Figure 1.3: Free PDF and ePub
Learn without limits with the following perks included with your purchase:
Learn from anywhere with a DRM-free PDF copy of this book.
Use your favorite e-reader to learn using a DRM-free ePub version of this book.
Unlock this book's exclusive benefits now
Scan this QR code or go to packtpub.com/unlock, then search for this book by name. Ensure it's the correct edition.
Note: Keep your purchase invoice ready before you start.
Technical requirements
The complete code for all the exercises and the activity in this chapter is available on GitHub at https://packt.link/EiB80.
Creating an Android project with Android Studio
In order to be productive building Android apps, it is essential to become confident in using Android Studio. This is the official integrated development environment (IDE) for Android development, built on JetBrains' IntelliJ IDEA IDE and developed by the Android Studio team at Google. You will use it throughout this book to create apps and progressively add more advanced features.
Since Google I/O 2017 (the annual Google developer conference), Kotlin has been Google's preferred programming language for Android app development. You will be using Kotlin throughout this book to build Android apps.
Kotlin was created to address some of the shortcomings of Java in terms of verbosity, handling null types, and adding more functional programming techniques, among many other issues.
Getting to grips with and familiarizing yourself with Android Studio will enable you to feel confident building Android apps. So, let's get started with creating your first project.
The installation and setup of Android Studio are covered in the Preface. Please ensure you have completed those steps before you continue.
Exercise 1.01 - Creating an Android Studio project for your app
This is the starting point for creating a project structure that your app will be built upon. The template-driven approach will enable you to create a basic project in a short timeframe while setting up the building blocks you can use to develop your app.
To complete this exercise, perform the following steps:
- Open Android Studio. You will see a window with side tabs and Projects highlighted. Select the New Project option on the right-hand side.
- Now, you'll enter a simple wizard-driven flow, which greatly simplifies the creation of your first Android project. The next screen you will see has many options for the initial setup you'd like your app to have:
Figure 1.4 - Starting a project template for your app
Welcome to your first introduction to the Android development ecosystem. The word displayed in most of the project types is Activity. In Android, an activity represents a single screen in your app that a user can interact with. When creating a new project, you can choose from different templates, each of which sets up the initial screen in a specific way. These templates determine how the first screen will look and provide a starting point for building your app. Select Empty Activity from the template and click on Next. The project configuration screen is as follows:
Figure 1.5 - Project configuration
Quick tip: Need to see a high-resolution version of this image? Open this book in the next-gen Packt Reader or view it in the PDF/ePub copy.
The next-gen Packt Reader and a free PDF/ePub copy of this book are included with your purchase. Scan the QR code OR visit packtpub.com/unlock, then use the search bar to find this book by name. Double-check the edition shown to make sure you get the right one.
The preceding screen configures your app. Let's go through all the options:
- Name: Similar to the name of your Android project, this name will appear as the default name of your app when it's installed on a phone and visible on Google Play.
- Package name: This uses the standard reverse domain name pattern to create a name. It will be used as an address identifier for source code and assets in your app. It's best to make this name as clear and descriptive and as closely aligned with the purpose of your app as possible. As shown in Figure 1.5, the Name value of the app,
My Application(in lowercase with spaces removed), is appended to the domain (com.example.myapplication). - Save location: This is the local folder on your machine where the app will initially be stored. By default, the project will be saved into a new folder with the name of the application with spaces removed. This results in a
MyApplicationproject folder being created. - Minimum SDK: Depending on which version of Android Studio you download, the default might be the same as shown in Figure 1.5 or a...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: ePUB
Copy protection: without DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Use a reader that can handle the file format ePUB, such as Adobe Digital Editions or FBReader – both free (see eBook Help).
- Tablet/Smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePUB works well for novels and non-fiction books – i.e., 'flowing' text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook does not use copy protection or Digital Rights Management
For more information, see our eBook Help page.