Android 9 Development Cookbook - Rick Boyer - E-Book

Android 9 Development Cookbook E-Book

Rick Boyer

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The Android OS has the largest installation base of any operating system in the world. There has never been a better time to learn Android development to write your own applications, or to make your own contributions to the open source community! With this extensively updated cookbook, you'll find solutions for working with the user interfaces, multitouch gestures, location awareness, web services, and device features such as the phone, camera, and accelerometer. You also get useful steps on packaging your app for the Android Market. Each recipe provides a clear solution and sample code you can use in your project from the outset. Whether you are writing your first app or your hundredth, this is a book that you will come back to time and time again, with its many tips and tricks on the rich features of Android Pie.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 431

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Android 9 Development CookbookThird Edition

 

Over 100 recipes and solutions to solve the most common problems faced by Android developers

 

 

 

 

 

 

 

Rick Boyer

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Android 9 Development Cookbook Third Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Amarabha BanerjeeAcquisition Editor: Larissa PintoContent Development Editor: Francis CarneiroTechnical Editor: Ralph RosarioCopy Editor: Safis EditingProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer:Priyanka DhadkeGraphics: Alishon MendonsaProduction Coordinator: Nilesh Mohite

First published: July 2011 Second edition: March 2016 Third edition: October 2018

Production reference: 2091118

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78899-121-6

www.packtpub.com

 

To my family for their patience while I focused on writing. To my mom, who is very excited about the book, even though she uses a phone from a different (unnamed) platform. And of course, to my wife Karen, for her encouragement and understanding!
 
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Contributors

About the author

 

Rick Boyer has been programming professionally for over 20 years. He has written apps on Windows, created websites, and coded for various mobile devices, including Windows CE, Windows Phone, and Android. Almost eight years ago, he took the plunge and started his own software consulting business, NightSky Development, focusing exclusively on Android development. 

I'd like to thank all the people at Packt Publishing for making this update to the book possible! A special thanks to the content development editor, Francis Carneiro, for his tireless efforts at keeping the book schedule. I'd also like to thank Emil Atanasov and Jason Morris for their technical review work. Your comments and corrections were much appreciated and made for a better book!

About the reviewers

Emil Atanasov is an IT consultant who has extensive experience with mobile technologies. He runs his own contracting and consulting company, serving clients from around the world: Appose Studio Inc. He is an MSc graduate of RWTH Aachen University, Germany, and Sofia University "St. Kliment Ohridski", Bulgaria. He has been a contractor for several large companies in the U.S. and U.K., serving variously as team leader, project manager, iOS developer, and Android developer. He teaches courses at Sofia University in Swift and iOS development. He is the author of Learn Swift by Building Applications and has served as technical reviewer and contributor on the following Packt titles: Objective C Memory Management and Android High-Performance Programming.

"I want to thank my wife, Elena, and my daughter, Sophia, and the rest of my family and friends for being very supportive, really patient, and super cool. Thank you for keeping me motivated through the endless working days. I know that, in your eyes, I'm a bizarre geeky person who is spending most of the time in the digital world. I appreciate your understanding. Thank you, guys!"

Jason Morris is a multi-discipline software developer and technical author. He has been developing software for as long as he can remember. He's written software for desktop, servers, feature phones, smartphones, the web, and even microcontrollers. Jason programs in a range of programming languages, and delights in knowing how software works. When he's not writing code, spending time with his family, or playing synthesizers, he's probably dreaming up a new code challenge. In 2010 through 2011, he wrote Android User Interface Development: A Beginner's Guide, and in 2017, he wrote Hands-On Android UI Development. On the internet, Jason is often known as "lemnik."

Thanks again to my wife and daughter for always being there.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Android 9 Development Cookbook Third Edition

Dedication

About Packt

Why subscribe?

Packt.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Get in touch

Reviews

Activities

Introduction

Declaring an activity

Getting ready

How to do it...

How it works...

Starting a new activity with an intent object

Getting ready

How to do it...

How it works...

There's more...

See also

Switching between activities

Getting ready

How to do it...

How it works...

See also

Passing data to another activity

Getting ready

How to do it...

How it works...

There's more...

Returning a result from an activity

Getting ready

How to do it...

How it works...

There's more...

See also

Saving an activity's state

Getting ready

How to do it...

How it works...

There's more...

See also

Storing persistent activity data

Getting ready

How to do it...

How it works...

There's more...

Using more than one preference file

See also

Understanding the activity life cycle

Getting ready

How to do it...

How it works...

There's more...

Layouts

Introduction

Defining and inflating a layout

Getting ready

How to do it...

How it works...

There's more...

See also

Using RelativeLayout

Getting ready

How to do it...

How it works...

There's more...

See also

Using LinearLayout

Getting ready

How to do it...

How it works...

There's more...

See also

Creating tables – TableLayout and GridLayout

Getting ready

How to do it...

How it works...

There's more...

RecyclerView replaces ListView

Getting ready

How to do it...

How it works…

There’s more…

Changing layout properties during runtime

Getting ready

How to do it...

How it works...

Views, Widgets, and Styles

Introduction

Inserting a widget into a layout

Getting ready

How to do it...

How it works...

There's more...

See also

Using graphics to show button state

Getting ready

How to do it...

How it works...

There's more...

Using designated folders for screen-specific resources

See also

Creating a widget at runtime

Getting ready

How to do it...

How it works...

There's more...

Creating a custom component

Getting ready

How to do it...

How it works...

There's more...

See also

Applying a style to a View

Getting ready

How to do it...

How it works...

There's more...

See also

Turning a style into a theme

Getting ready

How to do it...

How it works...

There's more...

Selecting a theme based on the Android version

Getting ready

How to do it...

How it works...

There's more...

Menus and Action Mode

Introduction

Creating an options menu

Getting ready

How to do it...

How it works...

There's more...

Using a menu item to launch an activity

Creating submenus

Grouping menu items

See also

Modifying menus and menu items during runtime

Getting ready

How to do it...

How it works...

There's more...

Enabling Contextual Action Mode for a view

Creating a floating context menu

Getting ready

How to do it...

How it works...

There's more...

See also

Using Contextual Batch Mode with RecyclerView

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a pop-up menu

Getting ready

How to do it...

How it works...

Fragments

Introduction

Creating and using a Fragment

Getting ready

How to do it...

How it works...

There's more...

See also

Adding and removing Fragments during runtime

Getting ready

How to do it...

How it works...

There's more...

See also

Passing data between Fragments

Getting ready

How to do it...

How it works...

There's more...

See also

Handling the Fragment back stack

Getting ready

How to do it...

How it works...

There's more...

Home Screen Widgets, Search, and the System UI

Introduction

Creating a shortcut on the Home screen

Getting ready

How to do it...

How it works...

There's more...

Creating a Home screen widget

Getting ready

How to do it...

How it works...

There's more...

See also

Adding Search to the Action Bar

Getting ready

How to do it...

How it works...

See also

Showing your app full-screen

Getting ready

How to do it...

How it works...

There's more...

Sticky Immersion

Dimming the System UI

Setting the Action Bar as an overlay

Translucent system bars

See also

Data Storage

Introduction

Storing simple data

Getting ready

How to do it...

How it works...

There's more...

Read and write a text file to internal storage

Getting ready

How to do it...

How it works...

There's more...

Caching files

See also

Read and write a text file to external storage

Getting ready

How to do it...

How it works...

There's more...

Getting public folders

Checking available space

Deleting a file

Working with directories

Preventing files from being included in galleries

See also

Including resource files in your project

Getting ready

How to do it...

How it works...

There's more...

See also

Creating and using an SQLite database

Getting ready

How to do it...

How it works...

There's more...

Upgrading a database

See also

Accessing data in the background using a Loader

Getting ready

How to do it...

How it works...

There's more...

See also

Accessing external storage with scoped directories in Android N

Getting ready

How to do it...

How it works...

There's more...

See also

Alerts and Notifications

Introduction

Lights, Action, and Sound – getting the user's attention!

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a Toast with a custom layout

Getting ready

How to do it...

How it works...

See also

Displaying a message box with AlertDialog

Getting ready

How to do it...

How it works...

There's more...

Add an icon

Using a list

Custom layout

Displaying a progress dialog

Getting ready

How to do it...

How it works...

There's more...

Lights, Action, and Sound Redux using Notifications

Getting ready

How to do it...

How it works...

There's more...

Adding a button to the notification using addAction()

Expanded notifications

Lock screen notifications

See also

Creating a Media Player Notification

Getting ready

How to do it...

How it works...

There's more...

See also

Making a Flashlight with a Heads-Up Notification

Getting ready

How to do it...

How it works...

There's more...

See also

Notifications with Direct Reply

Getting ready

How to do it...

How it works...

See also

Using the Touchscreen and Sensors

Introduction

Listening for click and long-press events

Getting ready

How to do it...

How it works...

There's more...

Recognizing tap and other common gestures

Getting ready

How to do it...

How it works...

There's more...

See also

Pinch-to-zoom with multi-touch gestures

Getting ready

How to do it...

How it works...

Swipe-to-Refresh

Getting ready

How to do it...

How it works...

There's more...

Listing available sensors – an introduction to the Android Sensor Framework

Getting ready

How to do it...

How it works...

There's more...

See also

Reading sensor data – using Android Sensor Framework events

Getting ready

How to do it...

How it works...

There's more...

Environment sensors

Position sensors

Motion sensors

See also

Reading device orientation

Getting ready

How to do it...

How it works...

There's more...

Getting current device rotation

See also

Graphics and Animation

Introduction

Scaling down large images to avoid Out of Memory exceptions

Getting ready

How to do it...

How it works...

There's more...

See also

A transition animation – defining scenes and applying a transition

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a Compass using sensor data and RotateAnimation

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a slideshow with ViewPager

Getting ready

How to do it...

How it works...

There's more...

Creating a Setup Wizard

See also

Creating a Card Flip Animation with Fragments

Getting ready

How to do it...

How it works...

See also

Creating a Zoom Animation with a Custom Transition

Getting ready

How to do it...

How it works...

There's more...

Getting the default animation duration

See also

Displaying animated image (GIF/WebP) with the new ImageDecoder library

Getting ready

How to do it...

How it works...

See also

Creating a circle image with the new ImageDecoder

Getting ready

How to do it...

How it works...

There's more...

See also

A First Look at OpenGL ES

Introduction

Setting up the OpenGL ES environment

Getting ready

How to do it...

How it works...

Declaring OpenGL in the Android Manifest

Extending the GLSurfaceView class

Creating an OpenGL rendered class

There's more...

Drawing shapes on GLSurfaceView

Getting ready

How to do it...

How it works...

There's more...

See also

Applying the projection and camera view while drawing

Getting ready

How to do it...

How it works...

There's more...

Moving the triangle with rotation

Getting ready

How to do it...

How it works...

There's more...

The render mode

Rotating the triangle with user input

Getting ready

How to do it...

How it works...

There's more...

See also

Multimedia

Introduction

Playing sound effects with SoundPool

Getting ready

How to do it...

How it works...

There's more...

See also

Playing audio with MediaPlayer

Getting ready

How to do it...

How it works...

There's more...

Playing music in the background

Using hardware volume keys to control your app's audio volume

See also

Responding to hardware media controls in your app

Getting ready

How to do it...

How it works...

There's more...

Checking the hardware type

See also

Taking a photo with the default camera app

Getting ready

How to do it...

How it works...

There's more...

Calling the default video app

See also

Taking a picture using the Camera2 API

Getting ready

How to do it...

How it works...

Setting up the camera preview

Capturing the image

There's more...

See also

Telephony, Networks, and the Web

Introduction

How to make a phone call

Getting ready

How to do it...

How it works...

See also

Monitoring phone call events

Getting ready

How to do it...

How it works...

There's more...

See also

How to send SMS (text) messages

Getting ready

How to do it...

How it works...

There's more...

Multipart messages

Delivery status notification

See also

Receiving SMS messages

Getting ready

How to do it...

How it works...

There's more...

Reading existing SMS messages

See also

Displaying a web page in your application

Getting ready

How to do it...

How it works...

There's more...

Controlling page navigation

How to enable JavaScript

Enable built-in zoom

See also

Checking online status and connection type

Getting ready

How to do it...

How it works...

There's more...

Monitoring network state changes

See also

Phone number blocking API

Getting ready

How to do it...

How it works...

There's more...

See also

Location and Using Geofencing

Introduction

How to get the device location

Getting ready

How to do it...

How it works...

There's more...

Mock locations

See also

Resolving problems reported with the GoogleApiClient OnConnectionFailedListener

Getting ready

How to do it...

How it works...

There's more...

See also

Creating and monitoring a Geofence

Getting ready

How to do it...

How it works...

There's more...

See also

Getting Your App Ready for the Play Store

Introduction

The Android 6.0 Runtime Permission Model

Getting ready

How to do it...

How it works...

There's more...

See also

How to schedule an alarm

Getting ready

How to do it...

How it works...

There's more...

Cancel the alarm

Repeating alarm

See also

Receiving notification of device boot

Getting ready

How to do it...

How it works...

There's more...

See also

Using the AsyncTask for background work

Getting ready

How to do it...

How it works...

There's more...

Parameter types

Canceling the task

See also

Adding speech recognition to your app

Getting ready

How to do it...

How it works...

There's more...

See also

How to add Google sign-in to your app

Getting ready

How to do it...

How it works...

There's more...

See also

Getting Started with Kotlin

Introduction

How to create an Android project with Kotlin

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a Toast in Kotlin

Getting ready

How to do it...

How it works...

See also

Runtime permission in Kotlin

Getting ready

How to do it...

How it works...

See also

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Android was first released in 2007 after being acquired by Google, Inc. Initially, Android was primarily used on a handset. Android 3.0 added features to take advantage of the growing tablet market.

In 2014, Google announced Android had over 1 billion active users! With over 1 million applications available on Google Play, there's never been a more exciting time to join the Android community!

This year, 2018, marks a significant milestone for Android - 10 year anniversary since the first Android phone was released! And with that, we have a new OS version release as well - Android Pie. In this new edition of the book, we'll cover features released for the platform in several new topics across many chapters, as well as updates to existing popular topics to cover SDK changes. As usual, the Android platform is constantly changing!

Who this book is for

This book assumes basic familiarity with programming concepts and Android fundamentals. Or, if you are new to Android and learn best by jumping into the code, this book provides a wide range of the most common tasks. If you are new to Android, you can start at the beginning of the book and work your way through the topics as they build on previous knowledge.

As a cookbook, the topics are designed to be stand-along (with noted exceptions), to make it easy to jump to a particular topic and get the code working in your own application as quickly as possible.

What this book covers

Chapter 1, Activities, the Activity represents the fundamental building block for most applications. See examples of the most common tasks such as creating an activity, and passing control from one activity to another. 

Chapter 2, Layouts, while Activities are fundamental to the UI, the Layout actually defines what the user sees on the screen. Learn the main layout options available and best to use cases. 

Chapter 3, Views, Widgets and Styles, explores the basic UI object, from which all layouts are built. The chapter starts by exploring views and widgets - the basic building block of any app then goes on to styling the widgets and turning those styles into themes.

Chapter 4, Menus and Action Mode, teaches you how to use menus in Android. Learn how to create menus and how to control their behavior at runtime, including Action Mode.

Chapter 5, Fragments, shows how to create more flexible user interfaces by reusing UI components with Fragments.

Chapter 6, Home Screen Widgets, Search and the System UI, takes us to topics outside your app such as how to create a widget for the Home Screen, adding search functionality UI to your app and running your app in full-screen mode.

Chapter 7, Data Storage, compares multiple methods Android offers for persisting data, and when best to use each option.

Chapter 8, Alerts and Notifications, shows multiple options for displaying notifications to your users. Options range from alerts in your application, using the system notification and the “Heads Up notification”. 

Chapter 9, Using the Touchscreen and Sensors, learn the events for handling the standard user interactions, such as button clicks, long presses, and gestures. Access the device hardware sensors to determine orientation changes, device movement, and compass bearing.

Chapter 10, Graphics and Animation, bring your app to life with animations! Take advantage of the many options Android offers for creating animations – from simple bitmaps to custom property animations.

Chapter 11, A first look at OpenGL ES, when you need high-performance 2D and 3D graphics, turn to the Open Graphics Library. Android supports Open GL, a cross-platform Graphics API.

Chapter 12, Multimedia - Sounds and Camera, take advantage of the hardware features for playing audio. Use Android intents to call the default camera application or delve into the camera APIs to control the camera directly.

Chapter 13, Telephony, Networks, and the Web, use the Telephony functions to initiate a phone call and to listen for incoming phone events. See how to send and receive SMS (text) messages. Use the WebView in your application to display web pages and learn to use Volley to communicate directly with web services.

Chapter 14, Location and using Geofencing, shows you how to determine the user's location and the best-practices so your app doesn’t drain the battery. Use the new Location APIs to receive location updates and create Geofences.

Chapter 15, Getting your app ready for the Play Store, as your polish your app for the Play Store, learn how to implement more advanced features such as Alarms, AsynchTask for background processing and add Google Sign-In to your app.

Chapter 16, Getting started with Kotlin, offers a first-look at the new Android language and several topics to get you started.

To get the most out of this book

You should know basic programming fundamentals. This book assumes the reader understands basic programming syntax and concepts. Language features such as

if

/

then

,

for next

and

try

/

catch

 should already be familiar and understood. 

Download and install the official Android development environment - Android Studio. Refer to the Hardware-Software List section for details.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Android-9-Development-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788991216_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

<activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter></activity>

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Activities

This chapter covers the following recipes:

Declaring an activity

Starting a new activity with an intent object

Switching between activities

Passing data to another activity

Returning a result from an activity

Saving an activity's state

Storing persistent activity data

Understanding the activity life cycle

Introduction

The Android SDK provides a powerful tool to program mobile devices, and the best way to master such a tool is to jump right in. Although you can read this book from beginning to end, as it is a cookbook, it is specifically designed to allow you to jump to specific tasks and get the results immediately.

Activities are the fundamental building block of most Android applications as the activity class provides the interface between the application and screen. Most Android applications will have at least one activity, if not several (but they are not required). A background service application will not necessarily require an activity if there is no user interface.

This chapter explains how to declare and launch activities within an application and how to manage several activities at once by sharing data between them, requesting results from them, and calling one activity from within another.

This chapter also briefly explores the intent object, which is often used in conjunction with activities. Intents can be used to transfer data between activities in your own application, as well as in external applications, such as those included with the Android operating system (a common example would be to use an intent to launch the default web browser).

To begin developing Android applications, head over to the Android Studio page to download the new Android Studio IDE and the Android SDK bundle:http://developer.android.com/sdk/index.html.

Declaring an activity

Activities and other application components, such as services, are declared in the AndroidManifest.xml file. Declaring an activity node is how we tell the OS about our Activity class and how it can be requested. For example, an application will usually indicate that at least one activity should be visible as a desktop icon and serve as the main entry point to the application.

Getting ready

Android Studio, now at version 3.2, is used for all the code samples shown in this book. If you have not already installed it, visit the Android Studio website (see the link in the previous tip) to install the IDE and the SDK bundle for your platform.

How to do it...

For this first example, we'll guide you through creating a new project. Android Studio provides a Quick Start wizard, which makes the process extremely easy. Follow these steps to get started:

Launch Android Studio, which brings up the

Welcome to Android Studio

dialog:

Click on the

Start a new Android Studio project

option.

Enter an application name; for this example, we used

DeclareAnActivity

. Click on

Next

:

In the

Target Android Devices

dialog, you can leave the

Phone and Tablet

checkbox selected with the default 

API 21: Android 5.0 (Lollipop)

 selection for the minimum SDK (for this example, it really doesn't matter which API level you choose, as activities have existed since API level 1). Click on

Next

:

In the

Add an

Activity to Mobile

dialog, select the

Empty Activity

option. Click on

Next

:

In the

Configure Activity

dialog, you can leave the defaults as provided, but note that the default activity name is

MainActivity

. Click on

Finish

:

After finishing the wizard, Android Studio will create the project files. For this recipe, the two files that we will examine are MainActivity.java (which corresponds to the activity name mentioned in step 6) and AndroidManifest.xml.

If you take a look at the MainActivity.java file, you will realize that it's pretty basic. This is because we chose the Empty Activity option (in step 5). Now, look at the AndroidManifest.xml file. This is where we actually declare the activity. Within the <application> element is the <activity> element:

<activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name= "android.intent.category.LAUNCHER"/> </intent-filter> </activity>

When viewing this xml in Android Studio, you may notice that the label element shows the actual text (DeclareAnActivity in this case) as defined in the strings.xml resource file.

How it works...

Declaring an activity is a simple matter of declaring the <activity> element and specifying the name of the activity class with the android:name attribute. By adding the <activity> element to the Android Manifest, we are specifying our intention to include this component in our application. Any activities (or any other component for that matter) that are not declared in the manifest will not be available to the application. Attempting to access or utilize an undeclared component will result in an exception being thrown at runtime.

In the preceding code, there is another attribute: android:label. This attribute indicates the title shown on the screen, as well as the icon if this is the Launcher activity.

For a complete list of available Activity attributes, take a look at this resource:http://developer.android.com/guide/topics/manifest/activity-element.html.

Starting a new activity with an intent object

The Android application model can be seen as a service-oriented one, with activities as components and intents as the messages sent between them. Here, an intent is used to start an activity that displays the user's call log, but intents can be used to do many things and we will encounter them throughout this book.

Getting ready

To keep things simple, we are going to use an intent object to start one of Android's built-in applications rather than create a new one. This only requires a very basic application, so start a new Android project with Android Studio and call it ActivityStarter.

How it works...

Though simple, this app demonstrates much of the power behind the Android OS. An intent is a message object. Intents can be used to communicate across your application's components (such as services and broadcast receivers) as well as with other applications on the device. In this recipe, we asked the OS to start any app that could handle the data we specified with the setData() method. (If the user has multiple browsers installed and no default set, the OS will show a list of apps for the user to choose from.)

To test this on a physical device, you may need to install drivers for your device (the drivers are specific to the hardware manufacturer). You will also need to enable Developer Mode on your device. Enabling Developer Mode varies according to the Android OS version. If you do not see the Developer Mode option in your device settings, open the About Phone option and begin tapping Build Number. After three taps, you should see a Toast message telling you that you are on your way to being a developer. Four more taps will enable the option.

In this recipe, we created an intent object with the ACTION_VIEW . as what we want to do (our intention). You may have noticed that when you typed Intent and the period, Android Studio provided a pop-up list of possibilities (this is the autocomplete feature), like this:

ACTION_VIEW, along with a URL in the data, indicates that the intention is to view the website, so the default browser is launched (different data could launch different apps). In this example, we just want to open a browser with the specified URL, so we call the startActivity() method. There are other ways to call the intent depending on our needs. In the Returning a result from an activity recipe, we will use the startActivityForResult() method.

There's more...

It's very common for Android users to download their favorite apps for web browsing, taking photos, text messaging, and so on. Using Intents, you allow your users to use their favorite apps instead of trying to reinvent all of this functionality.

See also

To start an activity from a menu selection, refer to the Handling menu selections recipe in Chapter 4, Menus and Action Mode.

Switching between activities

Often, we will want to activate one activity from within another activity. Although this is not a difficult task, it will require a little more setting up to be done than the previous recipes as it requires two activities. We will create two activity classes and declare them both in the manifest. We'll also create a button, as we did in the previous recipe, to switch to the activity.

Getting ready

We'll create a new project in Android Studio, just as we did in the previous recipes, and call this one ActivitySwitcher. Android Studio will create the first activity, ActivityMain, and automatically declare it in the manifest.

How it works...

The real work of this exercise is in the onClickSwitchActivity() method from step 3. This is where we declare the second activity for the Intent using SecondActivity.class. We went one step further by adding the close button to the second activity to show a common real-world situation: launching a new activity, then returning to the original calling activity. This behavior is accomplished in the onClickClose() function. All it does is call finish(), but that tells the OS that we're done with the activity. Finish doesn't actually return us to the calling activity (or any specific activity for that matter); it just closes the current activity and relies on the application's back stack to show the last activity. If we want a specific activity, we can again use the Intent object and specify the activity class name when creating the Intent.

This activity switching does not make a very exciting application. Our activity does nothing but demonstrates how to switch from one activity to another, which of course will form a fundamental aspect of almost any application that we develop.

If we had manually created the activities, we would need to add them to the manifest. Using the New Android Activity wizard will automatically add the necessary elements to the Android Manifest file. To see what Android Studio did for you, open the AndroidManifest.xml file and look at the <application> element:

<activity

android

:name=

".MainActivity"

>

<intent-filter>

<action

android

:name=

"android.intent.action.MAIN"

/>

<category

android

:name=

"android.intent.category.LAUNCHER"

/>

</intent-filter>

</activity>

<activity

android

:name=

".SecondActivity"

></activity>

One thing to note in the preceding auto-generated code is that the second activity does not have the <intent-filter> element. The main activity is generally the entry point when starting the application. That's why MAIN and LAUNCHER are defined so that the system will know which activity to launch when the application starts.

See also

To learn more about embedding widgets such as the Button, visit

Chapter 2

,

Views, Widgets, and Styles

Passing data to another activity

The intent object is defined as a messaging object. As a message object, its purpose is to communicate with other components of the application. In this recipe, we'll show you how to pass information with the intent and how to get it out again.

Getting ready

This recipe will pick up from where the previous one ended. We will call this project SendData.

How it works...

As expected, the Intent object is doing all the work. We created an intent just as in the previous recipe and then added some extra data. Did you notice the putExtra() method call? In our example, we used the already defined Intent.EXTRA_TEXT as the identifier, but we didn't have to. We can use any key we want (you've seen this concept before if you're familiar with name/value pairs).

The key point about using name/value pairs is that you have to use the same name to get the data back out. That's why we used the same key identifier when we read the extra data with getStringExtra().

The second activity was launched with the intent that we created, so it's simply a matter of getting the intent and checking for the data sent along with it. We do this in onCreate():

textView.setText(getIntent().getStringExtra(Intent.EXTRA_TEXT));

There's more...

We aren't limited to just sending String data. The intent object is very flexible and already supports basic data types. Go back to Android Studio and click on the putExtra method. Then, hit Ctrl and the spacebar. Android Studio will bring up the auto-complete list so that you can see the different data types that you can store.

Returning a result from an activity

Being able to start one activity from another is very useful and commonly used, but there are times when we need to know the result from the called activity. The startActivityForResult() method provides the solution.

Getting ready

Returning a result from an activity is not very different from the way we just called the activity in the previous recipes. You can either use the project from the previous recipe or start a new project and call it GettingResults. Either way, once you have a project with two activities and the code needed to call the second activity, you're ready to begin.

How it works...

As you can see, getting the results back is relatively straightforward. We just call the intent with startActivityForResult, indicating we want a result back. We set up the onActivityResult() callback handler to receive the results. Finally, we make sure that the second activity returns a result with setResult() before closing the activity. In this example, we are just setting a result with a static value. We use a simple Toast to display the result back to the user.

It's good practice to check the result code to make sure that the user didn't cancel the action. It's technically an integer, but the system uses it as a Boolean value. Check for either RESULT_OK or RESULT_CANCEL and proceed accordingly. In our example, the second activity doesn't have a cancel button, so why bother to check? What if the user hits the back button? Android will set the result code to RESULT_CANCEL