0% found this document useful (0 votes)
13 views

Android Final

kotlin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Android Final

kotlin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1185

Android Developer Fundamentals V2

Where is
everything?

This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
License.
Where is everything?

For a list of all the materials for the course,


see the course overview page at

developer.android.com/courses/adf-v2

This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
License.
Android Developer Fundamentals V2

Build your first


app
Lesson 1

This
Thiswork
workis islicensed
licensedunder
undera aCreative
Creative
Introduction
Introductiontoto
Android Developer Fundamentals V2 Commons
CommonsAttribution
Attribution4.0
4.0International
International 1
Android
Android
License.
License.
1.0 Introduction to Android

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
Android
License.
Contents

● Android is an ecosystem
● Android platform architecture
● Android Versions
● Challenges of Android app development
● App fundamentals

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
Android
License.
Android Ecosystem

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
Android
License.
What is Android?
● Mobile operating system based on Linux kernel
● User Interface for touch screens
● Used on over 80% of all smartphones
● Powers devices such as watches, TVs, and cars
● Over 2 Million Android apps in Google Play store
● Highly customizable for devices / by vendors
● Open source

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
Android
License.
Android user interaction
● Touch gestures: swiping, tapping, pinching
● Virtual keyboard for characters, numbers, and emoji
● Support for Bluetooth, USB controllers and peripherals

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
Android
License.
Android and sensors
Sensors can discover user action and respond
● Device contents rotate as needed
● Walking adjusts position on map
● Tilting steers a virtual car or controls a physical toy
● Moving too fast disables game interactions

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
Android
License.
Android home screen

● Launcher icons for apps


● Self-updating widgets for live content
● Can be multiple pages
● Folders to organize apps
● "OK Google"

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
Android
License.
Android app examples

Pandora Pokemon GO Facebook


Messenger
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
Android
License.
Android Software Developer Kit (SDK)
● Development tools (debugger, monitors, editors)
● Libraries (maps, wearables)
● Virtual devices (emulators)
● Documentation (developers.android.com)
● Sample code

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
Android
License.
Android Studio
● Official Android IDE
● Develop, run, debug,
test, and package apps
● Monitors and
performance tools
● Virtual devices
● Project views
● Visual layout editor

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
Android
License.
Google Play store
Publish apps through Google Play store:
● Official app store for Android
● Digital distribution service operated by Google

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
Android
License.
Android Platform
Architecture

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
Android
License.
Android stack

1. System and user apps


2. Android OS API in
Java framework
3. Expose native APIs;
run apps
4. Expose device
hardware capabilities
5. Linux Kernel

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
Android
License.
System and user apps

● System apps have no special status


● System apps provide key capabilities to app developers

Example:
Your app can use a system app to deliver a SMS
message.

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
Android
License.
Java API Framework
The entire feature-set of the Android OS is available to you
through APIs written in the Java language.

● View class hierarchy to create UI screens


● Notification manager
● Activity manager for life cycles and navigation

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
Android
License.
Android runtime

Each app runs in its own process with its own instance of the
Android Runtime.

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
Android
License.
C/C++ libraries

● Core C/C++ Libraries give access to core native Android


system components and services.

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
Android
License.
Hardware Abstraction Layer (HAL)

● Standard interfaces that expose device hardware


capabilities as libraries

Examples: Camera, bluetooth module

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
Android
License.
Linux Kernel

● Threading and low-level memory management


● Security features
● Drivers

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
Android
License.
Older Android versions
Codename Version Released API Level

Honeycomb 3.0 - 3.2.6 Feb 2011 11 - 13

Ice Cream Sandwich 4.0 - 4.0.4 Oct 2011 14 - 15

Jelly Bean 4.1 - 4.3.1 July 2012 16 - 18

KitKat 4.4 - 4.4.4 Oct 2013 19 - 20 Android History and


Platform Versions
Lollipop 5.0 - 5.1.1 Nov 2014 21 - 22 for more and earlier
versions before 2011
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
Android
License.
Newer Android versions
Codename Version Released API Level

Marshmallow 6.0 - 6.0.1 Oct 2015 23

Nougat 7.0 - 7.1 Sept 2016 24 - 25

Oreo 8.0 - 8.1 Sept 2017 26 - 27

Pie 9.0 Aug 2018 28

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
Android
License.
App Development

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
Android
License.
What is an Android app?

● One or more interactive screens


● Written using Java Programming Language and XML
● Uses the Android Software Development Kit (SDK)
● Uses Android libraries and Android Application
Framework
● Executed by Android Runtime Virtual machine (ART)
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
Android
License.
Challenges of Android development

● Multiple screen sizes and resolutions


● Performance: make your apps responsive and smooth
● Security: keep source code and user data safe
● Compatibility: run well on older platform versions
● Marketing: understand the market and your users
(Hint: It doesn't have to be expensive, but it can be.)

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
Android
License.
App building blocks

● Resources: layouts, images, strings, colors as XML and


media files
● Components: activities, services, and helper classes as
Java code
● Manifest: information about app for the runtime
● Build configuration: APK versions in Gradle config files

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
Android
License.
Learn more
● Android History
● Introduction to Android
● Platform Architecture
● UI Overview
● Platform Versions
● Supporting Different Platform Versions
● Android Studio User’s Guide

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
Android
License.
What's Next?

● Concept Chapter: 1.0 Introduction to Android


● No Practical

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals V2 Commons Attribution-NonCommercial 28
Android
4.0 International License
END

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 29
Android 4.0 International License
Android Developer Fundamentals V2

Build your first


app
Lesson 1

This
Thiswork
workis islicensed
licensedunder
undera aCreative
Creative
Your
Yourfirst
first
Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 Commons
CommonsAttribution
Attribution4.0
4.0International
International 1
Android
Android appapp
License.
License.
1.1 Your first Android app

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
Android app
License.
Contents

● Android Studio
● Creating "Hello World" app in Android Studio
● Basic app development workflow with Android Studio
● Running apps on virtual and physical devices

This work is licensed under a Creative


Create your first
Android Developer Fundamentals V2 Android app Commons Attribution 4.0 International 3
License.
Prerequisites
● Java Programming Language
● Object-oriented programming
● XML - properties / attributes
● Using an IDE for development and debugging

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
Android app
License.
Android Studio

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
Android app
License.
What is Android Studio?

● Android integrated development environment (IDE)


● Project and Activity templates
● Layout editor
● Testing tools
● Gradle-based build
● Log console and debugger
● Emulators

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
Android app
License.
Android Studio interface

1. Toolbar
2. Navigation bar
3. Project pane
4. Editor
5. Tabs for other
panes

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
Android app
License.
Installation Overview
● Mac, Windows, or Linux
● Download and install Android Studio from
https://developer.android.com/studio/
● See 1.1 P: Android Studio and Hello World

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
Android app
License.
Creating your
first Android app

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
Android app
License.
Start Android Studio

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
Android app
License.
Create a project inside Android Studio

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
Android app
License.
Name your app

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
Android app
License.
Pick activity template
Choose templates for
common activities,
such as maps or
navigation drawers.

Pick Empty Activity


or Basic Activity for
simple and custom
activities.
Your first This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
Android app
License.
Name your activity
● Good practice:
○ Name main activity
MainActivity
○ Name layout
activity_main
● Use AppCompat
● Generating layout
file is convenient

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
Android app
License.
Project folders
1. manifests—Android Manifest file -
description of app read by the
Android runtime
2. java—Java source code packages
3. res—Resources (XML) - layout,
strings, images, dimensions,
colors...
4. build.gradle—Gradle build files
Your first This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
Android app
License.
Gradle build system
● Modern build subsystem in Android Studio
● Three build.gradle:
○ project
○ module
○ settings

● Typically not necessary to know low-level Gradle details


● Learn more about gradle at https://gradle.org/
Your first This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
Android app
License.
Run your app
1. Run

2. Select virtual
or physical
device
3. OK
Your first This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17 17
Android app
License.
Create a virtual device
Use emulators to test app on different versions of Android and form factors.

Tools > Android > AVD Manager or:

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
Android app
License.
Configure virtual device

1. Choose hardware
2. Select Android version
3. Finalize

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
Android app
License.
Run on a virtual device

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
Android app
License.
Run on a physical device
1. Turn on Developer Options:
a. Settings > About phone
b. Tap Build number seven times
2. Turn on USB Debugging
a. Settings > Developer Options > USB Debugging
3. Connect phone to computer with cable

Windows/Linux additional setup:


● Using Hardware Devices

Windows drivers:
● OEM USB Drivers
Your first This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
Android app
License.
Get feedback as your app runs
1. Emulator
running the
app
2. Run pane
3. Run tab to
open or close
the Run pane

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
Android app
License.
Adding logging to your app
● As the app runs, the Logcat pane shows information
● Add logging statements to your app that will show up in the
Logcat pane
● Set filters in Logcat pane to see what's important to you
● Search using tags

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
Android app
License.
The Logcat pane
1. Logcat tab to
show Logcat
pane
2. Log level
menu

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
Android app
License.
Logging statement
import android.util.Log;

// Use class name as tag


private static final String TAG =
MainActivity.class.getSimpleName();

// Show message in Android Monitor, logcat pane


// Log.<log-level>(TAG, "Message");
Log.d(TAG, “Creating the URI…”);
Your first This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
Android app
License.
Learn more

● Meet Android Studio


● Official Android documentation at developer.android.com
● Create and Manage Virtual Devices
● Supporting Different Platform Versions
● Supporting Multiple Screens

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
Android app
License.
Learn even more

● Gradle Wikipedia page


● Google Java Programming Language style guide
● Find answers at Stackoverflow.com

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
Android app
License.
What's Next?

● Concept Chapter: 1.1 Your first Android app


● Practical: 1.1 Android Studio and Hello World

Your first This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
Android app
License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution-NonCommercial 29
4.0 International License
Android Developer Fundamentals V2

Build your first


app

Lesson 1

Layouts and This


Thiswork
workisislicensed
licensedunder
undera aCreative
Creative
AndroidDeveloper
Android DeveloperFundamentals
FundamentalsV2
V2 resources for the Commons
CommonsAttribution
Attribution4.0
4.0International
International 1
UI License.
License.
1.2 Layouts and resources
for the UI

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 2
UI License.
Contents

● Views, view groups, and view hierarchy


● The layout editor and ConstraintLayout
● Event handling
● Resources and measurements

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the UI Commons Attribution 4.0 International 3
License.
Views

Android Developer Fundamentals V2 4


Everything you see is a view
If you look at your mobile device,
every user interface element that you
see is a View.

Views

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 5
UI License.
What is a view?
View subclasses are basic user interface building blocks
● Display text (TextView class), edit text (EditText class)
● Buttons (Button class), menus, other controls
● Scrollable (ScrollView, RecyclerView)
● Show images (ImageView)
● Group views (ConstraintLayout and LinearLayout)
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 6
UI License.
Examples of view subclasses

Button CheckBox

EditText RadioButton

Slider Switch

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 7
UI License.
View attributes
● Color, dimensions, positioning
● May have focus (e.g., selected to receive user input)
● May be interactive (respond to user clicks)
● May be visible or not
● Relationships to other views

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 8
UI License.
Create views and layouts

● Android Studio layout editor: visual representation of XML


● XML editor
● Java code

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 9
UI License.
Android Studio layout editor
1. XML layout file
2. Design and Text
tabs
3. Palette pane
4. Component Tree
5. Design and
blueprint panes
6. Attributes tab

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 10
UI License.
View defined in XML
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/myBackgroundColor"
android:text="@string/count_initial_value"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/count_text_size"
android:textStyle="bold"
/>
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 11
UI License.
View attributes in XML
android:<property_name>="<property_value>"
Example: android:layout_width="match_parent"

android:<property_name>="@<resource_type>/resource_id"
Example: android:text="@string/button_label_next"

android:<property_name>="@+id/view_id"
Example: android:id="@+id/show_count"

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 12
UI License.
Create View in Java code
context
In an Activity:

TextView myText = new TextView(this);


myText.setText("Display this text!");

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 13
UI License.
What is the context?
● Context is an interface to global information about an
application environment
● Get the context:
Context context = getApplicationContext();
● An Activity is its own context:
TextView myText = new TextView(this);

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 14
UI License.
Custom views
● Over 100 (!) different types of views available from the
Android system, all children of the View class
● If necessary, create custom views by subclassing existing
views or the View class

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 15
UI License.
ViewGroup and
View hierarchy

Android Developer Fundamentals V2 16


ViewGroup contains "child" views
● ConstraintLayout: Positions UI elements using
constraint connections to other elements and to the
layout edges
● ScrollView: Contains one element and enables scrolling
● RecyclerView: Contains a list of elements and enables
scrolling by adding and removing elements dynamically

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 17
UI License.
ViewGroups for layouts
Layouts
● are specific types of ViewGroups (subclasses of
ViewGroup)
● contain child views
● can be in a row, column, grid, table, absolute

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 18
UI License.
Common Layout Classes

LinearLayout ConstraintLayout GridLayout TableLayout

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 19
UI License.
Common Layout Classes
● ConstraintLayout: Connect views with constraints
● LinearLayout: Horizontal or vertical row
● RelativeLayout: Child views relative to each other
● TableLayout: Rows and columns
● FrameLayout: Shows one child of a stack of children

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 20
UI License.
Class hierarchy vs. layout hierarchy
● View class-hierarchy is standard object-oriented class
inheritance
○ For example, Button is-a TextView is-a View is-an Object
○ Superclass-subclass relationship

● Layout hierarchy is how views are visually arranged


○ For example, LinearLayout can contain Buttons arranged in a
row
○ Parent-child relationship
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 21
UI License.
Hierarchy of viewgroups and views

ViewGroup Root view is always a ViewGroup

ViewGroup View View

View View View

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 22
UI License.
View hierarchy and screen layout

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 23
UI License.
View hierarchy in the layout editor

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 24
UI License.
Layout created in XML
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
... />
<TextView
... />
<Button
... />
</LinearLayout
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 25
UI License.
Layout created in Java Activity code
LinearLayout linearL = new LinearLayout(this);
linearL.setOrientation(LinearLayout.VERTICAL);

TextView myText = new TextView(this);


myText.setText("Display this text!");

linearL.addView(myText);
setContentView(linearL);

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 26
UI License.
Set width and height in Java code
Set the width and height of a view:
LinearLayout.LayoutParams layoutParams =
new Linear.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_CONTENT);
myView.setLayoutParams(layoutParams);

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the UI Commons Attribution 4.0 International 27
License.
Best practices for view hierarchies

● Arrangement of view hierarchy affects app performance


● Use smallest number of simplest views possible
● Keep the hierarchy flat—limit nesting of views and view
groups

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 28
UI License.
The layout
editor and
Constraint
Layout

Android Developer Fundamentals V2 29


The layout editor with ConstraintLayout

● Connect UI elements to parent


layout
● Resize and position elements
● Align elements to others
● Adjust margins and dimensions
● Change attributes
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 30
UI License.
What is ConstraintLayout?

● Default layout for new Android Studio project


● ViewGroup that offers flexibility for layout design
● Provides constraints to determine positions and
alignment of UI elements
● Constraint is a connection to another view, parent layout,
or invisible guideline

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 31
UI License.
Layout editor main toolbar

1. Select Design Surface: Design and Blueprint panes


2. Orientation in Editor: Portrait and Landscape
3. Device in Editor: Choose device for preview
4. API Version in Editor: Choose API for preview
5. Theme in Editor: Choose theme for preview
6. Locale in Editor: Choose language/locale for preview
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 32
UI License.
ConstraintLayout toolbar in layout editor

1. Show: Show Constraints and Show Margins


2. Autoconnect: Enable or disable
3. Clear All Constraints: Clear all constraints in layout
4. Infer Constraints: Create constraints by inference
5. Default Margins: Set default margins
6. Pack: Pack or expand selected elements
7. Align: Align selected elements
8. Guidelines: Add vertical or horizontal guidelines
9. Zoom controls: Zoom in or out
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 33
UI License.
Autoconnect

● Enable Autoconnect in
toolbar if disabled
● Drag element to any part
of a layout
● Autoconnect generates
constraints against
parent layout
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 34
UI License.
ConstraintLayout handles

1. Resizing handle
2. Constraint line and handle
3. Constraint handle
4. Baseline handle

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 35
UI License.
Align elements by baseline
1. Click the baseline
constraint button
2. Drag from baseline to
other element's baseline

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 36
UI License.
Attributes pane

● Click the Attributes tab


● Attributes pane includes:
○ Margin controls for
positioning
○ Attributes such as
layout_width

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 37
UI License.
Attributes pane view inspector
1. Vertical view size control specifies
layout_height
2. Horizontal view size control
specifies layout_width
3. Attributes pane close button

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 38
UI License.
Layout_width and layout_height
layout_width and layout_height change with size controls
● match_constraint: Expands element to fill its parent
● wrap_content: Shrinks element to enclose content
● Fixed number of dp (density-independent pixels)

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 39
UI License.
Set attributes

To view and edit all attributes for element:


1. Click Attributes tab
2. Select element in design, blueprint, or Component Tree
3. Change most-used attributes
4. Click at top or View more attributes at bottom to see
and change more attributes
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 40
UI License.
Set attributes example: TextView

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 41
UI License.
Preview layouts

Preview layout with horizontal/vertical orientation:


1. Click Orientation in Editor button
2. Choose Switch to Landscape or Switch to Portrait
Preview layout with different devices:
1. Click Device in Editor button
2. Choose device

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 42
UI License.
Create layout variant for landscape

1. Click Orientation in Editor button


2. Choose Create Landscape Variation
3. Layout variant created:
activity_main.xml (land)
4. Edit the layout variant as needed

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 43
UI License.
Create layout variant for tablet

1. Click Orientation in Layout Editor


2. Choose Create layout x-large Variation
3. Layout variant created: activity_main.xml (xlarge)
4. Edit the layout variant as needed

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 44
UI License.
Event Handling

Android Developer Fundamentals V2 45


Events

Something that happens


● In UI: Click, tap, drag
● Device: DetectedActivity such as walking, driving, tilting
● Events are "noticed" by the Android system

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 46
UI License.
Event Handlers

Methods that do something in response to a click


● A method, called an event handler, is triggered by a
specific event and does something in response to the
event

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 47
UI License.
Attach in XML and implement in Java
Attach handler to view in Implement handler in Java
XML layout: activity:
android:onClick="showToast" public void showToast(View view) {
String msg = "Hello Toast!";
Toast toast = Toast.makeText(
this, msg, duration);
toast.show();
}
}

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 48
UI License.
Alternative: Set click handler in Java
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String msg = "Hello Toast!";
Toast toast = Toast.makeText(this, msg, duration);
toast.show();
}
});
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 49
UI License.
Resources and
measurements

Android Developer Fundamentals V2 50


Resources

● Separate static data from code in your layouts.


● Strings, dimensions, images, menu text, colors, styles
● Useful for localization

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 51
UI License.
Where are the resources in your project?

resources and resource files


stored in res folder

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 52
UI License.
Refer to resources in code
● Layout:
R.layout.activity_main
setContentView(R.layout.activity_main);

● View:
R.id.recyclerview
rv = (RecyclerView) findViewById(R.id.recyclerview);

● String:
In Java: R.string.title
In XML: android:text="@string/title"
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 53
UI License.
Measurements
● Density-independent Pixels (dp): for Views
● Scale-independent Pixels (sp): for text

Don't use device-dependent or density-dependent units:


● Actual Pixels (px)
● Actual Measurement (in, mm)
● Points - typography 1/72 inch (pt)
Layouts and This work is licensed under a Creative
Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 54
UI License.
Learn more

Android Developer Fundamentals V2 55


Learn more
Views:
● View class documentation
● device independent pixels
● Button class documentation
● TextView class documentation
Layouts:
● developer.android.com Layouts
● Common Layout Objects

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 56
UI License.
Learn even more
Resources: Other:
● Android resources ● Android Studio documentation
● Color class definition ● Image Asset Studio
● R.color resources ● UI Overview
● Supporting Different Densities ● Vocabulary words and concepts
● Color Hex Color Codes glossary
● Model-View-Presenter
(MVP) architecture pattern
● Architectural patterns

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 57
UI License.
What's Next?

● Concept Chapter: 1.2 Layouts and resources for the UI


● Practicals:
○ 1.2A : Your first interactive UI

○ 1.2B : The layout editor

Layouts and This work is licensed under a Creative


Android Developer Fundamentals V2 resources for the Commons Attribution 4.0 International 58
UI License.
END

Android Developer Fundamentals V2 59


Android Developer Fundamentals V2

Build your first


app

Lesson 1

Text and This work is licensed under a Creative


Android
Android Developer
Developer Fundamentals
Fundamentals V2
V2 Commons Attribution 4.0 International 1
Scrolling Views
License.
1.3 Text and scrolling
views

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
Scrolling Views
License.
Contents

● TextView
● ScrollView

This work is licensed under a Creative


Text and Commons Attribution 4.0 International
Android Developer Fundamentals V2 3
Scrolling Views License.
TextView

Android Developer Fundamentals V2 4


TextView for text
● TextView is View subclass for single and multi-line text
● EditText is TextView subclass with editable text
● Controlled with layout attributes
● Set text:
○ Statically from string resource in XML
○ Dynamically from Java code and any source

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
Scrolling Views
License.
Formatting text in string resource
● Use <b> and <i> HTML tags for bold and italics
● All other HTML tags are ignored
● String resources: one unbroken line = one paragraph
● \n starts a new a line or paragraph
● Escape apostrophes and quotes with backslash (\", \')
● Escape any non-ASCII characters with backslash (\)
Text and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
Scrolling Views
License.
Creating TextView in XML

<TextView android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/my_story"/>

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
Scrolling Views
License.
Common TextView attributes
android:text—text to display
android:textColor—color of text
android:textAppearance—predefined style or theme
android:textSize—text size in sp
android:textStyle—normal, bold, italic, or bold|italic
android:typeface—normal, sans, serif, or monospace
android:lineSpacingExtra—extra space between lines in sp
Text and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
Scrolling Views
License.
Formatting active web links
<string name="article_text">... www.rockument.com ...</string>

<TextView
android:id="@+id/article"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="@string/article_text"/> Don’t use HTML
for a web link in
free-form text
autoLink values:"web", "email", "phone", "map", "all"

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
Scrolling Views
License.
Creating TextView in Java code
TextView myTextview = new TextView(this);
myTextView.setWidth(LayoutParams.MATCH_PARENT);
myTextView.setHeight(LayoutParams.WRAP_CONTENT);
myTextView.setMinLines(3);
myTextView.setText(R.string.my_story);
myTextView.append(userComment);

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
Scrolling Views
License.
ScrollView

Android Developer Fundamentals V2 11


What about large amounts of text?

● News stories, articles, etc…


● To scroll a TextView, embed it in a ScrollView
● Only one View element (usually TextView) allowed in a
ScrollView
● To scroll multiple elements, use one ViewGroup (such as
LinearLayout) within the ScrollView

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
Scrolling Views
License.
ScrollView for scrolling content
● ScrollView is a subclass of FrameLayout
● Holds all content in memory
● Not good for long texts, complex layouts
● Do not nest multiple scrolling views
● Use HorizontalScrollView for horizontal scrolling
● Use a RecyclerView for lists

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
Scrolling Views
License.
ScrollView layout with one TextView
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/article_subheading">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
.../>

</ScrollView>
Text and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
Scrolling Views
License.
ScrollView layout with a view group
<ScrollView ...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:id="@+id/article_subheading"
.../>

<TextView
android:id="@+id/article" ... />
</LinearLayout>
</ScrollView>

Text and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
Scrolling Views
License.
ScrollView with image and button
<ScrollView...>
One child of ScrollView
<LinearLayout...>
which can be a layout
<ImageView.../>
<Button.../> Children of the layout

<TextView.../>
</LinearLayout>
</ScrollView>
Text and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
Scrolling Views
License.
Learn more
Developer Documentation:
● TextView
● ScrollView and HorizontalScrollView
● String Resources
Other:
● Android Developers Blog: Linkify your Text!
● Codepath: Working with a TextView

This work is licensed under a Creative


Text and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
Scrolling Views
License.
What's Next?

● Concept Chapter: 1.3 Text and scrolling views


● Practical: 1.3 Text and scrolling views

This work is licensed under a Creative


Text and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
Scrolling Views
License.
END

Android Developer Fundamentals V2 19


Android Developer Fundamentals V2

Build your first


app
Lesson 1

This work
This work isislicensed
licensedunder
underaa Creative
Creative
Resources to help
Android
Android Developer
Developer Fundamentals
Fundamentals V2
V2 Commons Attribution 4.0 International
Commons 1
you learn License.
License.
1.4 Resources
to help you learn

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
you learn License.
Contents

● Documentation
● Tutorials and codelabs
● Blogs and videos
● Udacity courses
● Source code for the practicals

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
you learn
License.
Official Documentation
developer.android.com

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
you learn License.
Documentation Structure
Search

DESIGN - UX approach using “Material Design”

DEVELOP - Software Developer Information,


trainings, tutorials, sample code, reference

DISTRIBUTE - Delivering apps to users


This work is licensed under a Creative
Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
you learn License.
Stackoverflow.com
stackoverflow.com/questions/ tagged/android
Question/Answer format
Android, Java language, other programming topics

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
you learn License.
Official Android Blog
android.googleblog.com
News, features, high-level

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
you learn License.
Android Developers Blog
android-developers.blogspot.com
News, updates, developer stories, and articles on how to make
your app successful

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
you learn License.
Android Developers YouTube Channel
Android Developers YouTube channel
News, tools, how to, and playlists around specific themes, such as Android Developer
Patterns, Android Developer Stories, and Android Performance Patterns

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
you learn License.
Google IO Codelabs
codelabs.developers.google.com
Short tutorials
about specific topics

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
you learn License.
Online Udacity courses
www.udacity.com/courses/android
● Interactive video-based tutorials
● Android courses are built by Google
● Individual courses are free!
● Pay for a Nanodegree
○ build a portfolio of apps
○ get a certificate

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
you learn License.
Udacity Android Course Topics
www.udacity.com/courses/android

● Android for Beginners Advanced topics


● Developing Android Apps ● Performance
for programmers ● Material Design
● ...

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
you learn License.
Android Vocabulary tool
developers.google.com/android/for-all/vocab-words

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
you learn License.
Google Developer Training website
developers.google.com/training

● Course info
● Programs
● Certification details
● Authorized Training
Partners

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
you learn License.
Source code for exercises on github
https://github.com/google-developer-training/android-fundamentals

Starter code and solutions


for all the practicals and
many of the challenges

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
you learn License.
Download ZIP of repository (or clone)
1

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
you learn License.
Get the most from the practicals

● Complete each practical


● Study and learn the corresponding concepts
● Try completing the challenges
○ More detailed app that uses the concepts covered
○ Closer to real-world apps

This work is licensed under a Creative


Resources to help
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
you learn License.
Learn more
● Official Android documentation
● Get Android Studio
● Create App Icons with Image Asset Studio
● Official Android blog
● Android Developers blog
● Google I/O Codelabs
● Stack Overflow
● Android vocabulary
● Google Developer Training website

This work is licensed under a Creative


Resources to
Android Developer Fundamentals Commons Attribution 4.0 International 18
help you learn
License.
Learn even more
Code
● Source code for exercises on github
● Android code samples for developers

Videos
● Android Developer YouTube channel
● Udacity online courses

This work is licensed under a Creative


Resources to
Android Developer Fundamentals Commons Attribution 4.0 International 19
help you learn
License.
What's Next?

● Concept Chapter: 1.4 Resources to help you learn


● Practical: 1.4 Available resources

This work is licensed under a Creative


Resources to
Android Developer Fundamentals Commons Attribution 4.0 International 20
help you learn
License.
END

Android Developer Fundamentals V2 21


Android Developer Fundamentals V2

Activities and
Intents

Lesson 2

Activities and This work is licensed under a Creative


Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 Intents
Commons Attribution 4.0 International 1
License.
2.1 Activities and Intents

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 2
License.
Contents
● Activities
● Defining an Activity
● Starting a new Activity with an Intent
● Passing data between activities with extras
● Navigating between activities

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 3
License.
Activities
(high-level view)

Android Developer Fundamentals V2 4


What is an Activity?
● An Activity is an application component
● Represents one window, one hierarchy of views
● Typically fills the screen, but can be embedded in other
Activity or a appear as floating window
● Java class, typically one Activity in one file

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 5
License.
What does an Activity do?
● Represents an activity, such as ordering groceries,
sending email, or getting directions
● Handles user interactions, such as button clicks, text
entry, or login verification
● Can start other activities in the same or other apps
● Has a life cycle—is created, started, runs, is paused,
resumed, stopped, and destroyed
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 6
License.
Examples of activities

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 7
License.
Apps and activities
● Activities are loosely tied together to make up an app
● First Activity user sees is typically called "main activity"
● Activities can be organized in parent-child relationships in
the Android manifest to aid navigation

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 8
License.
Layouts and Activities
● An Activity typically has a UI layout
● Layout is usually defined in one or more XML files
● Activity "inflates" layout as part of being created

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 9
License.
Implementing
Activities

Android Developer Fundamentals V2 10


Implement new activities
1. Define layout in XML
2. Define Activity Java class
○ extends AppCompatActivity

3. Connect Activity with Layout


○ Set content view in onCreate()

4. Declare Activity in the Android manifest

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 11
License.
1. Define layout in XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Shop for Food!" />
</RelativeLayout>
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 12
License.
2. Define Activity Java class

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 13
License.
3. Connect activity with layout

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}
Resource is layout in this XML file
}

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 14
License.
4. Declare activity in Android manifest

<activity android:name=".MainActivity">

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 15
License.
4. Declare main activity in manifest
MainActivity needs to include intent-filter to start
from launcher
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 16
License.
Intents

Android Developer Fundamentals V2 17


What is an intent?
An Intent is a description of an operation to be performed.
An Intent is an object used to request an action from
another app component via the Android system.

Originator App component

Intent Action
Android
System
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 18
License.
What can intents do?
● Start an Activity
○ A button click starts a new Activity for text entry
○ Clicking Share opens an app that allows you to post a photo

● Start an Service
○ Initiate downloading a file in the background

● Deliver Broadcast
○ The system informs everybody that the phone is now charging
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 19
License.
Explicit and implicit intents
Explicit Intent
● Starts a specific Activity
○ Request tea with milk delivered by Nikita
○ Main activity starts the ViewShoppingCart Activity
Implicit Intent
● Asks system to find an Activity that can handle this request
○ Find an open store that sells green tea
○ Clicking Share opens a chooser with a list of apps
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 20
License.
Starting
Activities

Android Developer Fundamentals V2 21


Start an Activity with an explicit intent
To start a specific Activity, use an explicit Intent
1. Create an Intent
○ Intent intent = new Intent(this, ActivityName.class);

2. Use the Intent to start the Activity


○ startActivity(intent);

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 22
License.
Start an Activity with implicit intent
To ask Android to find an Activity to handle your request,
use an implicit Intent
1. Create an Intent
○ Intent intent = new Intent(action, uri);

2. Use the Intent to start the Activity


○ startActivity(intent);

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 23
License.
Implicit Intents - Examples
Show a web page
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 24
License.
How Activities Run
● All Activity instances are managed by the Android runtime
● Started by an "Intent", a message to the Android runtime to
run an activity
User clicks MainActivity FoodListActivity OrderActivity
launcher icon What do you want to do? Choose food items...Next Place order

Intent: Start app Start main Intent: Shop Start choose Intent: order Start finish
Android activity Android food activity Android order activity
System System System

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 25
License.
Sending and
Receiving Data

Android Developer Fundamentals V2 26


Two types of sending data with intents
● Data—one piece of information whose data location can
be represented by an URI

● Extras—one or more pieces of information as a collection


of key-value pairs in a Bundle

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 27
License.
Sending and retrieving data
In the first (sending) Activity:
1. Create the Intent object
2. Put data or extras into that Intent
3. Start the new Activity with startActivity()

In the second (receiving) Activity:


1. Get the Intent object, the Activity was started with
2. Retrieve the data or extras from the Intent object
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 28
License.
Putting a URI as intent data
// A web page URL
intent.setData(
Uri.parse("http://www.google.com"));

// a Sample file URI


intent.setData(
Uri.fromFile(new
File("/sdcard/sample.jpg")));
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 29
License.
Put information into intent extras
● putExtra(String name, int value)
⇒ intent.putExtra("level", 406);
● putExtra(String name, String[] value)
⇒ String[] foodList = {"Rice", "Beans", "Fruit"};
intent.putExtra("food", foodList);
● putExtras(bundle);
⇒ if lots of data, first create a bundle and pass the bundle.
● See documentation for all
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 30
License.
Sending data to an activity with extras
public static final String EXTRA_MESSAGE_KEY =
"com.example.android.twoactivities.extra.MESSAGE";

Intent intent = new Intent(this,


SecondActivity.class);
String message = "Hello Activity!";
intent.putExtra(EXTRA_MESSAGE_KEY, message);
startActivity(intent);

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 31
License.
Get data from intents
● getData();
⇒ Uri locationUri = intent.getData();
● int getIntExtra (String name, int defaultValue)
⇒ int level = intent.getIntExtra("level", 0);
● Bundle bundle = intent.getExtras();
⇒ Get all the data at once as a bundle.
● See documentation for all

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 32
License.
Returning data to the starting activity
1. Use startActivityForResult() to start the second Activity
2. To return data from the second Activity:
● Create a new Intent
● Put the response data in the Intent using putExtra()
● Set the result to Activity.RESULT_OK
or RESULT_CANCELED, if the user cancelled out
● call finish() to close the Activity
1. Implement onActivityResult() in first Activity
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 33
License.
startActivityForResult()
startActivityForResult(intent, requestCode);
● Starts Activity (intent), assigns it identifier (requestCode)
● Returns data via Intent extras
● When done, pop stack, return to previous Activity, and
execute onActivityResult() callback to process returned
data
● Use requestCode to identify which Activity has "returned"
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 34
License.
1. startActivityForResult() Example

public static final int CHOOSE_FOOD_REQUEST = 1;

Intent intent = new Intent(this, ChooseFoodItemsActivity.class);


startActivityForResult(intent, CHOOSE_FOOD_REQUEST);

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 35
License.
2. Return data and finish second activity
// Create an intent
Intent replyIntent = new Intent();

// Put the data to return into the extra


replyIntent.putExtra(EXTRA_REPLY, reply);

// Set the activity's result to RESULT_OK


setResult(RESULT_OK, replyIntent);

// Finish the current activity


finish();
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 36
License.
3. Implement onActivityResult()
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) { // Identify activity
if (resultCode == RESULT_OK) { // Activity succeeded
String reply =
data.getStringExtra(SecondActivity.EXTRA_REPLY);
// … do something with the data
}}}
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 37
License.
Navigation

Android Developer Fundamentals V2 38


Activity stack
● When a new Activity is started, the previous Activity
is stopped and pushed on the Activity back stack
● Last-in-first-out-stack—when the current Activity ends,
or the user presses the Back button, it is popped from the
stack and the previous Activity resumes

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 39
License.
Activity Stack
After viewing shopping
cart, user decides to add
more items, then places
order.

OrderActivity
Place order
CartActivity CartActivity
View shopping cart View shopping cart
FoodListActivity FoodListActivity FoodListActivity
Choose food items Choose food items Choose food items
MainActivity MainActivity MainActivity MainActivity
What do you want to do? What do you want to do? What do you want to do? What do you want to do?

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 40
License.
Two forms of navigation
Temporal or back navigation
● provided by the device's Back button
● controlled by the Android system's back stack

Ancestral or up navigation
● provided by the Up button in app's action bar
● controlled by defining parent-child relationships between
activities in the Android manifest
Activities and This work is licensed under a Creative
Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 41
License.
Back navigation
● Back stack preserves history of recently viewed screens
● Back stack contains all the Activity instances that have been
launched by the user in reverse order for the current task
● Each task has its own back stack
● Switching between tasks activates that task's back stack

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 42
License.
Up navigation
● Goes to parent of current Activity
● Define an Activity parent in Android manifest
● Set parentActivityName
<activity
android:name=".ShowDinnerActivity"
android:parentActivityName=".MainActivity" >
</activity>

Activities and This work is licensed under a Creative


Android Developer Fundamentals V2 Intents
Commons Attribution 4.0 International 43
License.
Learn more

Android Developer Fundamentals V2 44


Learn more
● Android Application Fundamentals
● Starting Another Activity
● Activity (API Guide)
● Activity (API Reference)
● Intents and Intent Filters (API Guide)
● Intent (API Reference)
● Navigation

This work is licensed under a Creative


Activities and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 45
Intents License.
What's Next?

● Concept Chapter: 2.1 Activities and Intents


● Practical: 2.1 Activities and intents

This work is licensed under a Creative


Activities and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 46
Intents License.
END

Android Developer Fundamentals V2 47


Android Developer Fundamentals V2

Activities and
Intents

Lesson 2

Activity lifecycle This work is licensed under a Creative


Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 and state
Commons Attribution 4.0 International 1
License.
2.2 Activity lifecycle
and state

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 2
License.
Contents

● Activity lifecycle
● Activity lifecycle callbacks
● Activity instance state
● Saving and restoring Activity state

Activity Lifecycle & This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
Managing State
License.
Activity lifecycle

Android Developer Fundamentals V2 4


What is the Activity Lifecycle?

● The set of states an Activity can be in during its lifetime,


from when it is created until it is destroyed

More formally:
● A directed graph of all the states an Activity can be in,
and the callbacks associated with transitioning from
each state to the next one

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 5
License.
What is the Activity Lifecycle?

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 6
License.
Activity states and app visibility
● Created (not visible yet)
● Started (visible)
● Resume (visible)
● Paused(partially invisible)
● Stopped (hidden)
● Destroyed (gone from memory)

State changes are triggered by user action, configuration


changes such as device rotation, or system action
Activity lifecycle This work is licensed under a Creative
Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 7
License.
Activity lifecycle
callbacks

Android Developer Fundamentals V2 8


Callbacks and when they are called
onCreate(Bundle savedInstanceState)—static initialization
onStart()—when Activity (screen) is becoming visible
onRestart()—called if Activity was stopped (calls onStart())
onResume()—start to interact with user
onPause()—about to resume PREVIOUS Activity
onStop()—no longer visible, but still exists and all state info preserved
onDestroy()—final call before Android system destroys Activity

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 9
License.
Activity states and callbacks graph

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 10
License.
Implementing and overriding callbacks
● Only onCreate() is required
● Override the other callbacks to change default behavior

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 11
License.
onCreate() –> Created
● Called when the Activity is first created, for example
when user taps launcher icon
● Does all static setup: create views, bind data to lists, ...
● Only called once during an activity's lifetime
● Takes a Bundle with Activity's previously frozen state, if
there was one
● Created state is always followed by onStart()
Activity lifecycle This work is licensed under a Creative
Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 12
License.
onCreate(Bundle savedInstanceState)

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
}

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 13
License.
onStart() –> Started

● Called when the Activity is becoming visible to user


● Can be called more than once during lifecycle
● Followed by onResume() if the activity comes to the
foreground, or onStop() if it becomes hidden

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 14
License.
onStart()

@Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 15
License.
onRestart() –> Started

● Called after Activity has been stopped, immediately before


it is started again
● Transient state
● Always followed by onStart()

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 16
License.
onRestart()

@Override
protected void onRestart() {
super.onRestart();
// The activity is between stopped and started.
}

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 17
License.
onResume() –> Resumed/Running

● Called when Activity will start interacting with user


● Activity has moved to top of the Activity stack
● Starts accepting user input
● Running state
● Always followed by onPause()

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 18
License.
onResume()

@Override
protected void onResume() {
super.onResume();
// The activity has become visible
// it is now "resumed"
}
Activity lifecycle This work is licensed under a Creative
Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 19
License.
onPause() –> Paused
● Called when system is about to resume a previous Activity
● The Activity is partly visible but user is leaving the Activity
● Typically used to commit unsaved changes to persistent data, stop
animations and anything that consumes resources
● Implementations must be fast because the next Activity is not
resumed until this method returns
● Followed by either onResume() if the Activity returns back to the front,
or onStop() if it becomes invisible to the user

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 20
License.
onPause()

@Override
protected void onPause() {
super.onPause();
// Another activity is taking focus
// this activity is about to be "paused"
}

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 21
License.
onStop() –> Stopped
● Called when the Activity is no longer visible to the user
● New Activity is being started, an existing one is brought
in front of this one, or this one is being destroyed
● Operations that were too heavy-weight for onPause()
● Followed by either onRestart() if Activity is coming back
to interact with user, or onDestroy() if Activity is going
away
Activity lifecycle This work is licensed under a Creative
Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 22
License.
onStop()

@Override
protected void onStop() {
super.onStop();
// The activity is no longer visible
// it is now "stopped"
}
Activity lifecycle This work is licensed under a Creative
Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 23
License.
onDestroy() –> Destroyed
● Final call before Activity is destroyed
● User navigates back to previous Activity, or configuration
changes
● Activity is finishing or system is destroying it to save space
● Call isFinishing() method to check
● System may destroy Activity without calling this, so use
onPause() or onStop() to save data or state

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 24
License.
onDestroy()

@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 25
License.
Activity instance
state

Android Developer Fundamentals V2 26


When does config change?
Configuration changes invalidate the current layout or other
resources in your activity when the user:
● Rotates the device
● Chooses different system language, so locale changes
● Enters multi-window mode (from Android 7)

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 27
License.
What happens on config change?
On configuration change, Android:
1. Shuts down Activity 2. Starts Activity over again
by calling: by calling:
● onPause() ● onCreate()
● onStop() ● onStart()
● onDestroy() ● onResume()

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 28
License.
Activity instance state
● State information is created while the Activity is running,
such as a counter, user text, animation progression

● State is lost when device is rotated, language changes,


back-button is pressed, or the system clears memory

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 29
License.
Saving and
restoring
Activity state

Android Developer Fundamentals V2 30


What the system saves
● System saves only:
○ State of views with unique ID (android:id) such as
text entered into EditText
○ Intent that started activity and data in its extras

● You are responsible for saving other activity and user


progress data

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 31
License.
Saving instance state

Implement onSaveInstanceState() in your Activity

● Called by Android runtime when there is a possibility the


Activity may be destroyed
● Saves data only for this instance of the Activity during
current session

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 32
License.
onSaveInstanceState(Bundle outState)
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Add information for saving HelloToast counter
// to the to the outState bundle
outState.putString("count",
String.valueOf(mShowCount.getText()));
}

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 33
License.
Restoring instance state
Two ways to retrieve the saved Bundle
● in onCreate(Bundle mySavedState)
Preferred, to ensure that your user interface, including any
saved state, is back up and running as quickly as possible
● Implement callback (called after onStart())
onRestoreInstanceState(Bundle mySavedState)

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 34
License.
Restoring in onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowCount = findViewById(R.id.show_count);

if (savedInstanceState != null) {
String count = savedInstanceState.getString("count");
if (mShowCount != null)
mShowCount.setText(count);
}
}
Activity lifecycle This work is licensed under a Creative
Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 35
License.
onRestoreInstanceState(Bundle state)

@Override
public void onRestoreInstanceState (Bundle mySavedState) {
super.onRestoreInstanceState(mySavedState);

if (mySavedState != null) {
String count = mySavedState.getString("count");
if (count != null)
mShowCount.setText(count);
}
}

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 36
License.
Instance state and app restart

When you stop and restart a new app session, the Activity
instance states are lost and your activities will revert to their
default appearance

If you need to save user data between app sessions, use


shared preferences or a database.

Activity lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 and state
Commons Attribution 4.0 International 37
License.
Learn more
● Activities (API Guide)
● Activity (API Reference)
● Managing the Activity Lifecycle
● Pausing and Resuming an Activity
● Stopping and Restarting an Activity
● Recreating an Activity
● Handling Runtime Changes
● Bundle
Activity Lifecycle This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 38
and State
License.
What's Next?

● Concept Chapter: 2.2 Activity lifecycle and state


● Practical: 2.2 Activity lifecycle and state

Activity Lifecycle This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 39
and State
License.
END

Android Developer Fundamentals V2 40


Android Developer Fundamentals V2

Activities and
Intents
Lesson 2

This work is licensed under a Creative


Android
Android Developer
DeveloperFundamentals
Fundamentals V2
V2 Implicit Intents Commons Attribution 4.0 International 1
License.
2.3 Implicit Intents

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 2
License.
Contents

● Intent—recap
● Implicit Intent overview
● Sending an implicit Intent
● Receiving an implicit Intent

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 3
License.
Recap: Intent

Android Developer Fundamentals V2 4


What is an Intent?
An Intent is:
● Description of an operation to be performed
● Messaging object used to request an action from another
app component via the Android system.
Originator App component

Intent Action
Android
System

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 5
License.
What can an Intent do?
An Intent can be used to:
● start an Activity
● start a Service
● deliver a Broadcast

Services and Broadcasts are covered in other lessons


This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 6
License.
Explicit vs. implicit Intent

Explicit Intent — Starts an Activity of a specific class

Implicit Intent — Asks system to find an Activity class with a


registered handler that can handle this request

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 7
License.
Implicit Intent
overview

Android Developer Fundamentals V2 8


What you do with an implicit Intent

● Start an Activity in another app by describing an action you


intend to perform, such as "share an article", "view a map",
or "take a picture"
● Specify an action and optionally provide data with which to
perform the action
● Don't specify the target Activity class, just the intended
action
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 9
License.
What system does with implicit Intent
● Android runtime matches the implicit intent request with
registered intent handlers
● If there are multiple matches, an App Chooser will open to
let the user decide

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 10
License.
How does implicit Intent work?
1. The Android Runtime keeps a list of registered Apps
2. Apps have to register via AndroidManifest.xml
3. Runtime receives the request and looks for matches
4. Android runtime uses Intent filters for matching
5. If more than one match, shows a list of possible matches
and lets the user choose one
6. Android runtime starts the requested activity

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 11
License.
App Chooser

When the Android runtime finds


multiple registered activities that can
handle an implicit Intent, it displays an
App Chooser to allow the user to select
the handler

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 12
License.
Sending an
implicit Intent

Android Developer Fundamentals V2 13


Sending an implicit Intent
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);

User has pressed Call button — start Activity that can make
a call (no data is passed in or returned)

1. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 14
License.
Avoid exceptions and crashes
Before starting an implicit Activity, use the package manager
to check that there is a package with an Activity that matches
the given criteria.

Intent myIntent = new Intent(Intent.ACTION_CALL_BUTTON);

if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 15
License.
Sending an implicit Intent with data URI
1. Create an Intent for action
Intent intent = new Intent(Intent.ACTION_DIAL);

1. Provide data as a URI


intent.setData(Uri.parse("tel:8005551234"));

1. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 16
License.
Providing the data as URI

Create an URI from a string using Uri.parse(String uri)

● Uri.parse("tel:8005551234")
● Uri.parse("geo:0,0?q=brooklyn%20bridge%2C%20brooklyn%2C%20ny")
● Uri.parse("http://www.android.com");

Uri documentation

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 17
License.
Implicit Intent examples
Show a web page
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 18
License.
Sending an implicit Intent with extras
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);

1. Put extras
String query = edittext.getText().toString();
intent.putExtra(SearchManager.QUERY, query));

1. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 19
License.
Category
Additional information about the kind of component to
handle the intent.
● CATEGORY_OPENABLE
Only allow URIs of files that are openable
● CATEGORY_BROWSABLE
Only an Activity that can start a web browser to display
data referenced by the URI
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 20
License.
Sending an implicit Intent with type and category

1. Create an Intent for an action


Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

1. Set mime type and category for additional information


intent.setType("application/pdf"); // set MIME type
intent.addCategory(Intent.CATEGORY_OPENABLE);

continued on next slide...

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 21
License.
Sending an implicit Intent with type and category

3. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(myIntent,ACTIVITY_REQUEST_CREATE_FILE);
}

4. Process returned content URI in onActivityResult()

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 22
License.
Common actions for an implicit Intent
Common actions include:
● ACTION_SET_ALARM
● ACTION_IMAGE_CAPTURE
● ACTION_CREATE_DOCUMENT
● ACTION_SENDTO
● and many more
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 23
License.
Apps that handle common actions
Common actions are usually handled by installed apps (both
system apps and other apps), such as:

● Alarm Clock, Calendar, Camera, Contacts ➔ List of common


● Email, File Storage, Maps, Music/Video actions for an
implicit intent
● Notes, Phone, Search, Settings
➔ List of all
● Text Messaging and Web Browsing available actions

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 24
License.
Receiving an
Implicit Intent

Android Developer Fundamentals V2 25


Register your app to receive an Intent
● Declare one or more Intent filters for the Activity in
AndroidManifest.xml
● Filter announces ability of Activity to accept an implicit
Intent
● Filter puts conditions on the Intent that the Activity accepts

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 26
License.
Intent filter in AndroidManifest.xml
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 27
License.
Intent filters: action and category

● action — Match one or more action constants


○ android.intent.action.VIEW — matches any Intent with ACTION_VIEW
○ android.intent.action.SEND — matches any Intent with ACTION_SEND

● category — additional information (list of categories)


○ android.intent.category.BROWSABLE—can be started by web browser
○ android.intent.category.LAUNCHER—Show activity as launcher icon

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 28
License.
Intent filters: data

● data — Filter on data URIs, MIME type


○ android:scheme="https"—require URIs to be https protocol
○ android:host="developer.android.com"—only accept an Intent from
specified hosts
○ android:mimeType="text/plain"—limit the acceptable types of documents

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 29
License.
An Activity can have multiple filters
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
...
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
...
</intent-filter>
</activity> An Activity can have several filters
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 30
License.
A filter can have multiple actions & data
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
<data android:mimeType="video/*"/>
</intent-filter>

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 31
License.
Learn more

Android Developer Fundamentals V2 32


Learn more

● Intent class documentation


● Uri documentation
● List of common apps that respond to implicit intents
● List of available actions
● List of categories
● Intent Filters
This work is licensed under a Creative
Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 33
License.
What's Next?

● Concept Chapter: 2.3 Implicit Intents


● Practical: 2.3 Implicit Intents

This work is licensed under a Creative


Android Developer Fundamentals V2 Implicit Intents Commons Attribution 4.0 International 34
License.
END

Android Developer Fundamentals V2 35


Android Developer Fundamentals V2

Testing, debugging,
and using support
libraries

Lesson 3

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
Studio debugger License.
3.1 The Android Studio
debugger

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
Studio debugger License.
Contents
● All code has bugs
● Android Studio logging
● Android Studio debugger
● Working with breakpoints
● Changing variables
● Stepping through code
The Android Studio This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
debugger
License.
All Code Has
Bugs

Android Developer Fundamentals V2 4


Bugs
● Incorrect or unexpected result, wrong values
● Crashes, exceptions, freezes, memory leaks
● Causes
○ Human Design or Implementation Error > Fix your code
○ Software fault, but in libraries > Work around limitation
○ Hardware fault or limitation -> Make it work with what's available

Origin of the term "bug" (it's not what you think)

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
Studio debugger License.
Debugging

● Find and fix errors


● Correct unexpected and undesirable behavior

● Unit tests help identify bugs and prevent regression


● User testing helps identify interaction bugs

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
Studio debugger License.
Android Studio debugging tools

Android Studio has tools that help you

● identify problems
● find where in the source code the problem is created
● so that you can fix it

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
Studio debugger License.
Logging with
Android Studio

Android Developer Fundamentals V2 8


Add Log messages to your code
import android.util.Log;

// Use class variable with class name as tag


private static final String TAG =
MainActivity.class.getSimpleName();

// Show message in Logcat pane of Android Studio


// Log.<log-level>(TAG, "Message");
Log.d(TAG, “Hello World”);
This work is licensed under a Creative
The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
Studio debugger License.
Open Logcat pane

Logcat
pane

Logcat
tab
This work is licensed under a Creative
The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
Studio debugger License.
Inspect logging messages

Log.d("MainActivity", "Hello World");

09-12 14:28:07.971 4304 /com.example.android.helloworld D/MainActivity: Hello World

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
Studio debugger License.
Choose visible logging level

Displays logs with levels at


this level or higher

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
Studio debugger License.
Log Levels

● Verbose - All verbose log statements and comprehensive system


● Debug - All debug logs, variable values, debugging notes

● Info - Status info, such as database connection

● Warning - Unexpected behavior, non-fatal issues

● Error - Serious error conditions, exceptions, crashes only

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
Studio debugger License.
Debugging with
Android
Studio

Android Developer Fundamentals V2 14


What you can do
● Run in debug mode with attached debugger
● Set and configure breakpoints
● Halt execution at breakpoints
● Inspect execution stack frames and variable values
● Change variable values
● Step through code line by line
● Pause and resume a running program
This work is licensed under a Creative
The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
Studio debugger License.
Run in debug mode
1

Debugger pane opens Menu:


2 Run > Debug 'your app'

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
Studio debugger License.
Set breakpoints

Click in the left margin next


to executable line of code

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
Studio debugger License.
Edit breakpoint properties

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
Studio debugger License.
Make breakpoints conditional
● In properties dialog or right -click existing breakpoint
● Any Java expression that returns a boolean
● Code completion helps you write conditions

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
Studio debugger License.
Run until app stops at breakpoint

First Breakpoint

Frames Variables in scope Watches (C/C++)

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
Studio debugger License.
Inspect frames

Top frame is where execution is


halted in your code

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
Studio debugger License.
Inspect and edit variables

● Right-click on variable for menu

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
Studio debugger License.
Basic Stepping Commands
Step Over F8 Step to the next line in current file
Step Into F7 Step to the next executed line

Force Step Into ⇧F7 Step into a method in a class that you wouldn't
normally step into, like a standard JDK class

Step Out ⇧F8 Step to first executed line after returning from
current method

Run to Cursor ⌥F9 Run to the line where the cursor is in the file

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
Studio debugger License.
Stepping through code

Show execution point Drop frame Run to cursor

Step over Step into Step out


Force step into
This work is licensed under a Creative
The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
Studio debugger License.
Resume and Pause

Resume

Pause

Mute all
breakpoints Menu:
Run->Pause Program…
Run->Resume Program...
This work is licensed under a Creative
The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
Studio debugger License.
Learn more

● Debug Your App (Android Studio User Guide)


● Debugging and Testing in Android Studio (video)

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
Studio debugger License.
What's Next?

● Concept Chapter: 3.1 The Android Studio debugger


● Practical: 3.1 The debugger

This work is licensed under a Creative


The Android
Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
Studio debugger License.
END

Android Developer Fundamentals V2 28


Android Developer Fundamentals V2

Testing, debugging,
and using support
libraries

Lesson 3

This work is licensed under a Creative


Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 App testing Commons Attribution 4.0 International 1
License.
3.2 App testing

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 2
License.
Contents

● Why testing is worth your time


● Unit testing

Note: User interface testing (instrumented testing) is


covered in another chapter

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 3
License.
Testing rocks

Android Developer Fundamentals V2 4


Why should you test your app?
● Find and fix issues early
● Less costly
● Takes less effort Cost to Fix
Catch bugs
● Costs to fix bugs $1000 early!
increases with time $100

$10

$1 Specification Design Code QA Release


Discovery Time
This work is licensed under a Creative
Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 5
License.
Types of testing
● Levels of Testing
○ Component, integration, protocol, system

● Types of Testing
○ Installation, compatibility, regression, acceptance
○ Performance, scalability, usability, security

● User interface and interaction tests


○ Automated UI testing tools
○ Instrumented testing (covered in another chapter)
This work is licensed under a Creative
Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 6
License.
Test-Driven Development (TDD)
1. Define a test case for a requirement
2. Write tests that assert all conditions of the test case
3. Write code against the test
4. Iterate on and refactor code until it passes the test
5. Repeat until all requirements have test cases, all tests
pass, and all functionality has been implemented

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 7
License.
Tests in your project

Android Studio creates three source sets for your project


● main—code and resources
● (test)—local unit tests
● (androidTest)—instrumented tests

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 8
License.
Local Unit Tests

Android Developer Fundamentals V2 9


Unit tests
● Smallest testable parts of your program
● Isolate each component and demonstrate the individual
parts are correct
● Java Method tests
Results
Inputs Java method
Graceful Failure

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 10
License.
Local unit tests in JUnit
● Compiled and run entirely on your local machine with the Java Virtual
Machine (JVM)
● Use to test the parts of your app (such as the internal logic):
○ If you don't need access to Android framework or device/emulator
○ If you can create fake (mock) objects that pretend to behave like the
framework equivalents
● Unit tests are written with JUnit, a common unit testing framework for Java.

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 11
License.
Local unit tests in your project
● Tests are in the same package as the associated
application class
● Only org.junit imported — no Android classes
● Project path for test classes: .../module-
name/src/test/java/

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 12
License.
Imports for JUnit
// Annotations
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

// Basic JUnit4 test runner


import org.junit.runners.JUnit4;

// assertThat method
import static org.junit.Assert.assertThat;

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 13
License.
Testing class

/**
* JUnit4 unit tests for the calculator logic.
* These are local unit tests; no device needed
*/
@RunWith(JUnit4.class) // Specify the test runner
public class CalculatorTest { // Name it what you are testing
}

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 14
License.
ExampleTest
/
**
* Test for simple addition.
* Each test is identified by a @Test annotation.
*/
@Test
public void addTwoNumbers() {
double resultAdd = mCalculator.add(1d, 1d);
assertThat(resultAdd, is(equalTo(2d)));
}

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 15
License.
@Test Annotation
● Tells JUnit this method is a test method (JUnit 4)
● Information to the test runner
● Not necessary anymore to prefix test methods with "test"

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 16
License.
setUp() method
/**
* Set up the environment for testing
*/
@Before
public void setUp() {
mCalculator = new Calculator();
}

● Sets up environment for testing


● Initialize variables and objects used in multiple tests

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 17
License.
tearDown() method
/**
* Release external resources
*/
@After
public void tearDown() {
....
}

● Frees resources

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 18
License.
Running tests in
Android Studio

Android Developer Fundamentals V2 19


Starting a test run
● Right-click test class and select
Run 'app_name' test
● Right-click test package and select
Run tests in 'package'

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 20
License.
Passing and failing
Pass
Fail Fail
Pass

Result details

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 21
License.
Testing floating
point results

Android Developer Fundamentals V2 22


Testing floating point
● Be careful with floating point tests
● Recall from basic computer science:
○ Floating point arithmetic is not accurate in binary

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 23
License.
Test fails with floating point numbers

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 24
License.
Fix test with floating point numbers

They are the same


within .0005 in this test

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 25
License.
Learn more
● Getting Started with Testing
● Best Practices for Testing
● Building Local Unit Tests
● JUnit 4 Home Page
● JUnit 4 API Reference
● Android Testing Codelab
● Android Tools Protip: Test Size Annotations
● Android Testing Support - Testing Patterns (video)
This work is licensed under a Creative
Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 26
License.
What's Next?

● Concept Chapter: 3.2 App testing


● Practical: 3.2 Unit tests

This work is licensed under a Creative


Android Developer Fundamentals V2 App testing Commons Attribution 4.0 International 27
License.
END

Android Developer Fundamentals V2 28


Android Developer Fundamentals V2

Testing, debugging,
and using support
libraries

Lesson 3

This work is licensed under a Creative


Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 The
TheAndroid
Android Commons Attribution 4.0 International 1
Support
SupportLibrary
Library License.
3.3 The Android Support
Library

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 2
Support Library License.
Contents

● What are the Android support libraries?


● Features
● Selected libraries
● Setting up and using support libraries

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 3
Support Library License.
What are the Android support libraries?

● More than 25 libraries in the Android SDK that provide


features not built into the Android framework

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 4
Support Library License.
Features

Android Developer Fundamentals V2 5


Support library features
Support libraries provide:
● Backward-compatible versions of components
● Additional layout and UI elements, such as RecyclerView
● Different form factors, such as TV, wearables
● Material design and other new UI components for older
Android versions
● and more….
This work is licensed under a Creative
Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 6
Support Library License.
Backward compatibility

Always use the the support library version of a component if


one is available
● No need to create different app versions for different
versions of Android
● System picks the best version of the component

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 7
Support Library License.
Support libraries versions

● Libraries for Android 2.3 (API level 9) and higher


● Recommended you include the v4 support and
v7 appcompat libraries for the features your app uses

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 8
Support Library License.
Libraries

Android Developer Fundamentals V2 9


v4 Support Libraries

● Largest set of APIs


● App components, UI features
● Data handling
● Network connectivity
● Programming utilities

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 10
Support Library License.
v4 Support Libraries

● compat—compatibility wrappers
● core-utils—utility classes (eg., AsyncTaskLoader)
● core-ui—variety of UI components
● media-compat—back ports of media framework
● fragment—UI component

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 11
Support Library License.
v7 Support Libraries
● Backwards compatibility
● TV-specific components
● UI components and layouts
● Google Cast support
● Color palette
● Preferences
This work is licensed under a Creative
Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 12
Support Library License.
v7 Support Libraries
● appcompat—compatibility wrappers
● cardview— new UI component (material design)
● gridlayout—rectangular cell (matrix) Layout
● mediarouter—route A/V streams
● palette—extracting color from an image
● recyclerview—efficient scrolling view
● preference—modifying UI settings
This work is licensed under a Creative
Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 13
Support Library License.
v7 appcompat library

● ActionBar and sharing actions


● You should always include this library and make
AppCompatActivity the parent of your activities
com.android.support:appcompat-v7:27.1.1

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 14
Support Library License.
Complete list of libraries

● … and many more


● For latest libraries and versions of libraries
○ Support Library Features documentation
○ API Reference (all packages that start with android.support)

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 15
Support Library License.
Using
support libraries

Android Developer Fundamentals V2 16


Support libraries

● Part of Android SDK and available through SDK Manager


● In Android Studio, locally stored in Android Support
Repository
● Include in build.gradle of module to use with your project

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 17
Support Library License.
Start SDK Manager in Android Studio

1. Tools > Android > SDK Manager

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 18
Support Library License.
Find the Android Support Library
1. SDK Tools tab
2. Find Android Support Repository
3. Must be Installed

If Not Installed or Update Available


1. Check checkbox and Apply
2. In dialog, confirm components
and click OK to install
3. When done, click Finish
4. Verify that it is Installed now

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 19
Support Library License.
Find the dependency identifier
1. Open Support Library Features page
2. Find the feature you want
○ For example, the recommended v7 appcompat library
3. Copy the build script dependency identifier for the library
○ com.android.support:appcompat-v7:26.1.0

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 20
Support Library License.
Add dependency to build.gradle
1. open build.gradle (Module: app)
2. In the dependencies section, add dependency for
support library if not already included from template
○ implementation 'com.android.support:appcompat-v7:26.1.0'

3. Update the version number, if prompted


4. Sync Now when prompted

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 21
Support Library License.
Updated build.gradle (Module: app)
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation
'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation
'com.android.support.test:runner:1.0.1'
androidTestImplementation
'com.android.support.test.espresso:espresso-core:3.0.1'
}

This work is licensed under a Creative


Android Developer Fundamentals V2 The Android Commons Attribution 4.0 International 22
Support Library License.
Learn more

● Android Support Library (introduction)


● Support Library Setup
● Support Library Features
● API Reference (all packages that start with android.support

This work is licensed under a Creative


The Android Commons Attribution 4.0 International
Android Developer Fundamentals V2 23
Support Libraries License.
What's Next?

● Concept Chapter: 3.3 The Android Support Library


● Practical: 3.3 Support libraries

This work is licensed under a Creative


The Android Commons Attribution 4.0 International
Android Developer Fundamentals V2 24
Support Libraries License.
END

Android Developer Fundamentals V2 25


Android Developer Fundamentals V2

User Interaction

Lesson 4

Buttons
Buttonsand
and This work is licensed under a Creative
Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 clickable
clickableimages
images
Commons Attribution 4.0 International 1
License.
4.1 Buttons and clickable
images

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 2
License.
Contents
● User interaction
● Buttons
● Clickable images
● Floating action button
● Common gestures

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
clickable images
License.
User interaction

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 4
License.
Users expect to interact with apps

● Tapping or clicking, typing, using gestures, and talking


● Buttons perform actions
● Other UI elements enable data input and navigation

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
clickable images
License.
User interaction design
Important to be obvious, easy, and consistent:
● Think about how users will use your app
● Minimize steps
● Use UI elements that are easy to access, understand, use
● Follow Android best practices
● Meet user's expectations
Buttons and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
clickable images
License.
Buttons

Android Developer Fundamentals V2 7


Button
● View that responds to tapping (clicking) or pressing
● Usually text or visuals indicate what will happen when
tapped
● State: normal, focused, disabled, pressed, on/off

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 8
License.
Button image assets

1. Right-click app/res/drawable
2. Choose New > Image Asset
3. Choose Action Bar and Tab Items
from drop down menu
4. Click the Clipart: image Experiment:
(the Android logo) 2. Choose New > Vector Asset

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 9
License.
Responding to button taps
● In your code: Use OnClickListener event listener.
● In XML: use android:onClick attribute in the XML layout:
<Button
android:id="@+id/button_send" android:onClick
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 10
License.
Setting listener with onClick callback

Button button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 11
License.
Clickable
images

Android Developer Fundamentals V2 12


ImageView
● ImageView with android:onClick attribute
● Image for ImageView in app>src>main>res>drawable
folder in project

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 13
License.
Responding to ImageView taps
● In your code: Use OnClickListener event listener.
● In XML: use android:onClick attribute in the XML layout:

<ImageView
android:layout_width="wrap_content" android:onClick
android:layout_height="wrap_content"
android:src="@drawable/donut_circle"
android:onClick="orderDonut"/>

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 14
License.
Floating action
button

Android Developer Fundamentals V2 15


Floating Action Buttons (FAB)

● Raised, circular, floats above layout


● Primary or "promoted" action for a screen
● One per screen

For example:
Add Contact button in Contacts app

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 16
License.
Using FABs
● Start with Basic Activity template
● Layout:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/ic_fab_chat_button_white"
.../>

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 17
License.
FAB size

● 56 x 56 dp by default
● Set mini size (30 x 40 dp) with app:fabSize attribute:
○ app:fabSize="mini"

● Set to 56 x 56 dp (default):
○ app:fabSize="normal"

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 18
License.
Common
Gestures

Android Developer Fundamentals V2 19


Touch Gestures
Touch gestures include:
● long touch
● double-tap Don’t depend on touch
● fling gestures for app's basic
● drag behavior!
● scroll
● pinch

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 20
License.
Detect gestures
Classes and methods are available to help you handle
gestures.
● GestureDetectorCompat class for common gestures
● MotionEvent class for motion events

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 21
License.
Detecting all types of gestures
1. Gather data about touch events.
2. Interpret the data to see if it meets the criteria for any
of the gestures your app supports.
Read more about how to handle gestures in the
Android developer documentation

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 22
License.
Learn more
● Input Controls ● Buttons
● Drawable Resources ● Spinners
● Floating Action Button ● Dialogs
● Radio Buttons ● Fragments
● Specifying the Input ● Input Events
Method Type ● Pickers
● Handling Keyboard Input ● Using Touch Gestures
● Text Fields ● Gestures design guide
Buttons and This work is licensed under a Creative
Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 23
License.
What's Next?

● Concept Chapter: 4.1 Buttons and clickable images


● Practical: 4.1 Clickable images

Buttons and This work is licensed under a Creative


Android Developer Fundamentals V2 clickable images
Commons Attribution 4.0 International 24
License.
END

Android Developer Fundamentals V2 25


Android Developer Fundamentals V2

User Interaction

Lesson 4

This work is licensed under a Creative


Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 Input Controls Commons Attribution 4.0 International 1
License.
4.2 Input Controls

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 2
License.
Contents

● Overview of input controls


● View focus
● Freeform text and numbers
● Providing choices

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 3
License.
Overview of
input Controls

Android Developer Fundamentals V2 4


Accepting user input

● Freeform text and numbers: EditText (using keyboard)


● Providing choices: CheckBox, RadioButton, Spinner
● Switching on/off: Toggle, Switch
● Choosing value in range of values: SeekBar

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 5
License.
Examples of input controls

1. EditText
2. SeekBar
3. CheckBox
4. RadioButton
5. Switch
6. Spinner

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 6
License.
How input controls work
1. Use EditText for entering text using keyboard
2. Use SeekBar for sliding left or right to a setting
3. Combine CheckBox elements for choosing more than
one option
4. Combine RadioButton elements into RadioGroup —
user makes only one choice
5. Use Switch for tapping on or off
6. Use Spinner for choosing a single item from a list
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 7
License.
View is base class for input controls
● The View class is the basic building block for all UI
components, including input controls
● View is the base class for classes that provide interactive UI
components
● View provides basic interaction through android:onClick

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 8
License.
View focus

Android Developer Fundamentals V2 9


Focus
● The View that receives user input has "Focus"
● Only one View can have focus
● Focus makes it unambiguous which View gets the input
● Focus is assigned by
○ User tapping a View
○ App guiding the user from one text input control to the next using
the Return, Tab, or arrow keys
○ Calling requestFocus() on any View that is focusable

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 10
License.
Clickable versus focusable

Clickable—View can respond to being clicked or tapped


Focusable—View can gain focus to accept input
Input controls such as keyboards send input to the view that
has focus

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 11
License.
Which View gets focus next?

● Topmost view under the touch


● After user submits input, focus moves to nearest
neighbor—priority is left to right, top to bottom
● Focus can change when user interacts with a directional
control

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 12
License.
Guiding users

● Visually indicate which view has focus so users knows


where their input goes
● Visually indicate which views can have focus helps users
navigate through flow
● Predictable and logical—no surprises!

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 13
License.
Guiding focus
● Arrange input controls in a layout from left to right and top
to bottom in the order you want focus assigned
● Place input controls inside a view group in your layout
● Specify ordering in XML
android:id="@+id/top"
android:focusable="true"
android:nextFocusDown="@+id/bottom"
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 14
License.
Set focus explicitly

Use methods of the View class to set focus


● setFocusable() sets whether a view can have focus
● requestFocus() gives focus to a specific view
● setOnFocusChangeListener() sets listener for when view
gains or loses focus
● onFocusChanged() called when focus on a view changes
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 15
License.
Find the view with focus

● Activity.getCurrentFocus()
● ViewGroup.getFocusedChild()

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 16
License.
Freeform text
and numbers

Android Developer Fundamentals V2 17


EditText for multiple lines of text

● EditText default
● Alphanumeric keyboard
● Suggestions appear
● Tapping Return (Enter) key starts
new line

Return key
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 18
License.
Customize with inputType

● Set in Attributes pane of layout editor

● XML code for EditText:


<EditText
android:id="@+id/name_field"
android:inputType =
"textPersonName"
...

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 19
License.
EditText for message
● android:inputType
="textShortMessage"
● Single line of text
● Tapping Emoticons key changes
keyboard to emoticons

Emoticons
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 20
License.
EditText for single line
● Both work:
○ android:inputType
="textLongMessage"
○ android:inputType
="textPersonName"
● Single line of text
● Tapping Done key advances focus
to next View Done key
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 21
License.
EditText for phone number entry

● android:inputType ="phone"
● Numeric keypad (numbers only)
● Tapping Done key advances focus
to next View

Done key
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 22
License.
Getting text

● Get the EditText object for the EditText view


EditText simpleEditText =
findViewById(R.id.edit_simple);

● Retrieve the CharSequence and convert it to a string


String strValue =
simpleEditText.getText().toString();
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 23
License.
Input types
Common input types
● textCapCharacters: Set to all capital letters
● textCapSentences: Start each sentence with a capital letter
● textPassword: Conceal an entered password
● number: Restrict text entry to numbers
● textEmailAddress: Show keyboard with @ conveniently located
● phone: Show a numeric phone keypad
● datetime: Show a numeric keypad with a slash and colon for entering
the date and time

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 24
License.
Providing
choices

Android Developer Fundamentals V2 25


UI elements for providing choices
● CheckBox and RadioButton

● ToggleButton and Switch

● Spinner

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 26
License.
CheckBox

● User can select any number of choices


● Checking one box does not uncheck another
● Users expect checkboxes in a vertical list
● Commonly used with a Submit button
● Every CheckBox is a View and can have
an onClick handler

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 27
License.
RadioButton
● Put RadioButton elements in a RadioGroup in a
vertical list (horizontally if labels are short)
● User can select only one of the choices
● Checking one unchecks all others in group
● Each RadioButton can have onClick
handler
● Commonly used with a Submit button
for the RadioGroup
This work is licensed under a Creative
Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 28
License.
Toggle buttons and switches
● User can switch between on and off
● Use android:onClick for click handler

Toggle buttons

Switches

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 29
License.
Learn more
● Input Controls
● Radio Buttons
● Specifying the Input Method Type
● Handling Keyboard Input
● Text Fields
● Spinners

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 30
License.
What's Next?

● Concept Chapter: 4.2 Input controls


● Practical: 4.2 Input controls

This work is licensed under a Creative


Android Developer Fundamentals V2 Input Controls Commons Attribution 4.0 International 31
License.
END

Android Developer Fundamentals V2 32


Android Developer Fundamentals V2

User Interaction

Lesson 4

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Menus and pickers Commons Attribution 4.0 International 1
pickers License.
4.3 Menus and pickers

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
pickers License.
Contents
● Overview
● App Bar with Options Menu
● Contextual menus
● Popup menus
● Dialogs
● Pickers
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
pickers
License.
Overview

Android Developer Fundamentals V2 4


Types of Menus
1. App bar with options
menu
2. Context menu
3. Contextual action bar
4. Popup menu

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
pickers License.
Dialogs and pickers

1. Alert dialog
2. Date picker
3. Time picker

1 2 3

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
pickers
License.
App Bar with
Options Menu

Android Developer Fundamentals V2 7


What is the App Bar?
Bar at top of each screen—same for all devices (usually)
1. Nav icon to open navigation drawer
2. Title of current Activity
3. Icons for options menu items
4. Action overflow button for
the rest of the options menu

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
pickers License.
What is the options menu?
● Action icons in the app bar
for important items (1)
● Tap the three dots, the
"action overflow button" to
see the options menu (2)
● Appears in the right corner of the app bar (3)
● For navigating to other activities and editing app settings
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
pickers License.
Adding Options
Menu

Android Developer Fundamentals V2 10


Steps to implement options menu
1. XML menu resource (menu_main.xml)
2. onCreateOptionsMenu() to inflate the menu
3. onClick attribute or onOptionsItemSelected()
4. Method to handle item click

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
pickers License.
Create menu resource
1. Create menu resource directory
2. Create XML menu resource (menu_main.xml)
3. Add entry for each menu item (Settings and Favorites):

<item android:id="@+id/option_settings"
android:title="Settings" />
<item android:id="@+id/option_favorites"
android:title="Favorites" />

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
pickers License.
Inflate options menu
Override onCreateOptionsMenu() in Activity

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
pickers License.
Add icons for menu items
1. Right-click drawable
2. Choose New > Image Asset
3. Choose Action Bar and Tab Items
4. Edit the icon name
5. Click clipart image, and click icon
6. Click Next, then Finish
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
pickers License.
Add menu item attributes

<item
android:id="@+id/action_favorites"
android:icon="@drawable/ic_favorite"
android:orderInCategory="30"
android:title="@string/action_favorites"
app:showAsAction="ifRoom" />

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
pickers License.
Override onOptionsItemSelected()
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
showSettings();
return true;
case R.id.action_favorites:
showFavorites();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
pickers License.
Contextual
Menus

Android Developer Fundamentals V2 17


What are contextual menus?

● Allows users to perform action on selected View


● Can be deployed on any View
● Most often used for items in RecyclerView, GridView, or
other View collection

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
pickers License.
Types of contextual menus
● Floating context menu—long-press on a View
○ User can modify View or use it in some fashion
○ User performs action on one View at a time

● Contextual action mode—temporary action bar in


place of or underneath app bar
○ Action items affect the selected View element(s)
○ User can perform action on multiple View elements at once

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
pickers License.
Floating Context
Menu

Android Developer Fundamentals V2 20


Steps

1. Create XML menu resource file and assign appearance and position attributes
2. Register View using registerForContextMenu()
3. Implement onCreateContextMenu() in Activity to inflate menu
4. Implement onContextItemSelected() to handle menu item clicks
5. Create method to perform action for each context menu item

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
pickers License.
Create menu resource
1. Create XML menu resource (menu_context.xml)
<item
android:id="@+id/context_edit"
android:title="Edit"
android:orderInCategory="10"/>

<item
android:id="@+id/context_share"
android:title="Share"
android:orderInCategory="20"/>
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
pickers License.
Register a view to a context menu

In onCreate() of the Activity:


2. Register View.OnCreateContextMenuListener to View:

TextView article_text = findViewById(R.id.article);


registerForContextMenu(article_text);

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
pickers License.
Implement onCreateContextMenu()
onCreateContextMenu() method
3. Specify which context menu

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
}

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
pickers License.
Implement onContextItemSelected()
onCreateContextMenu()
@Override method
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_edit:
editNote();
return true;
case R.id.context_share:
shareNote();
return true;
default:
return super.onContextItemSelected(item);
}
}
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
pickers License.
Contextual
Action Bar

Android Developer Fundamentals V2 26


What is Action Mode?
● UI mode that lets you replace parts of normal UI
interactions temporarily
● For example: Selecting a section of text or long-pressing
an item could trigger action mode

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
pickers License.
Action mode has a lifecycle
● Start it with startActionMode(), for example, in the listener
● ActionMode.Callback interface provides lifecycle methods you override:
○ onCreateActionMode(ActionMode, Menu) once on initial creation
○ onPrepareActionMode(ActionMode, Menu) after creation and any time
ActionMode is invalidated
○ onActionItemClicked(ActionMode, MenuItem) any time contextual action
button is clicked
○ onDestroyActionMode(ActionMode) when action mode is closed

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
pickers License.
What is a contextual action bar?
Long-press on View shows contextual action bar
1. Contextual action bar with actions
○ Edit, Share, and Delete
○ Done (left arrow icon) on left side
○ Action bar is available until user taps Done

2. View on which long press triggers


contextual action bar
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 29
pickers License.
Steps for contextual action bar
1. Create XML menu resource file and
assign icons for items
2. setOnLongClickListener() on View
that triggers contextual action
bar and call startActionMode() to
handle click
3. Implement ActionMode.Callback interface to handle ActionMode lifecycle;
include action for menu item click in onActionItemClicked() callback
4. Create method to perform action for each context menu item

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 30
pickers License.
Use setOnLongClickListener
private ActionMode mActionMode;

In onCreate():
View view = findViewById(article);
view.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mActionMode != null) return false;
mActionMode =
MainActivity.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 31
pickers License.
Implement mActionModeCallback

public ActionMode.Callback mActionModeCallback =


new ActionMode.Callback() {
// Implement action mode callbacks here.
};

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 32
pickers License.
Implement onCreateActionMode

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_context, menu);
return true;
}

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 33
pickers License.
Implement onPrepareActionMode
● Called each time action mode is shown
● Always called after onCreateActionMode, but may be called multiple times if
action mode is invalidated

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done.
}

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 34
pickers License.
Implement onActionItemClicked
● Called when users selects an action
● Handle clicks in this method
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_share:
// Perform action for the Share menu item.
mode.finish(); // Action picked, so close the action bar.
return true;
default:
return false;
}
}
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 35
pickers License.
Implement onDestroyActionMode

● Called when user exits the action mode

@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 36
pickers License.
Popup Menu

Android Developer Fundamentals V2 37


What is a popup menu?
● Vertical list of items anchored to a view
● Typically anchored to a visible icon
● Actions should not directly affect view content
○ Options menu overflow icon that opens options menu
○ In email app, Reply All and Forward relate to email message but
don’t affect or act on message

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 38
pickers License.
Steps

1. Create XML menu resource file and assign appearance and position attributes
2. Add ImageButton for the popup menu icon in the XML activity layout file
3. Assign onClickListener to ImageButton
4. Override onClick() to inflate the popup and register it with
onMenuItemClickListener()
5. Implement onMenuItemClick()
6. Create a method to perform an action for each popup menu item
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 39
pickers License.
Add ImageButton

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_popup"
android:src="@drawable/@drawable/ic_action_popup"/>

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 40
pickers License.
Assign onClickListener to button
private ImageButton mButton =
(ImageButton) findViewById(R.id.button_popup);

In onCreate():

mButton.setOnClickListener(new View.OnClickListener() {
// define onClick
});

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 41
pickers License.
Implement onClick
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, mButton);
popup.getMenuInflater().inflate(
R.menu.menu_popup, popup.getMenu());
popup.setOnMenuItemClickListener(
new PopupMenu.OnMenuItemClickListener() {
// implement click listener.
});
popup.show();
}
This work is licensed under a Creative
Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 42
pickers License.
Implement onMenuItemClick
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.option_forward:
// Implement code for Forward button.
return true;
default:
return false;
}
}

This work is licensed under a Creative


Menus and
Android Developer Fundamentals V2 Commons Attribution 4.0 International 43
pickers License.
Dialogs

Android Developer Fundamentals V2 44


Dialogs
● Dialog appears on top,
interrupting flow of Activity
● Requires user action to dismiss

TimePickerDialog DatePickerDialog AlertDialog


Menus and This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 45
pickers
License.
AlertDialog
AlertDialog can show:
1. Title (optional)
2. Content area
3. Action buttons

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 46
pickers
License.
Build the AlertDialog
Use AlertDialog.Builder to build alert dialog and set
attributes:

public void onClickShowAlert(View view) {


AlertDialog.Builder alertDialog = new
AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Connect to Provider");
alertDialog.setMessage(R.string.alert_message);
// ... Code to set buttons goes here.

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 47
pickers
License.
Set the button actions
● alertDialog.setPositiveButton()
● alertDialog.setNeutralButton()
● alertDialog.setNegativeButton()

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 48
pickers
License.
alertDialog code example
alertDialog.setPositiveButton(
"OK", newDialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User clicked OK button.
}
});

Same pattern for setNegativeButton() and setNeutralButton()

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 49
pickers
License.
Pickers

Android Developer Fundamentals V2 50


Pickers
● DatePickerDialog
● TimePickerDialog

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 51
pickers
License.
Pickers use fragments
● Use DialogFragment to show a picker
● DialogFragment is a window that floats
on top of Activity window

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 52
pickers
License.
Introduction to fragments
● A Fragment is like a mini-Activity within an Activity
○ Manages its own own lifecycle
○ Receives its own input events

● Can be added or removed while parent Activity is running


● Multiple fragments can be combined in a single Activity
● Can be reused in more than one Activity

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 53
pickers
License.
Creating a date picker dialog
1. Add a blank Fragment that extends DialogFragment and
implements DatePickerDialog.OnDateSetListener
2. In onCreateDialog() initialize the date and return the
dialog
3. In onDateSet() handle the date
4. In Activity show the picker and add method to use date

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 54
pickers
License.
Creating a time picker dialog
1. Add a blank Fragment that extends DialogFragment and
implements TimePickerDialog.OnTimeSetListener
2. In onCreateDialog() initialize the time and return the
dialog
3. In onTimeSet() handle the time
4. In Activity, show the picker and add method to use time

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 55
pickers
License.
Learn more
● Adding the App Bar
● Menus
● Menu Resource
● Fragments
● Dialogs
● Pickers
● Drawable Resources

Menus and This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 56
pickers
License.
What's Next?

● Concept Chapter: 4.3 Menus and pickers


● Practical: 4.3 Menus and pickers

This work is licensed under a Creative


Menus and Commons Attribution 4.0 International
Android Developer Fundamentals V2 57
pickers License.
END

Android Developer Fundamentals V2 58


Android Developer Fundamentals V2

User Interaction

Lesson 4

This work is licensed under a Creative


Android
AndroidDeveloper
DeveloperFundamentals
FundamentalsV2
V2 User
Usernavigation
navigation Commons Attribution 4.0 International 1
License.
4.4 User navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 2
License.
Contents
● Back navigation
● Hierarchical navigation
○ Up navigation
○ Descendant navigation
● Navigation drawer for descendant navigation
○ Lists and carousels for descendant navigation
○ Ancestral navigation
○ Lateral navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 3
License.
Two forms of navigation
Back (temporal) navigation
● Provided by the device's Back button
● Controlled by the Android system back stack

Ancestral (Up) navigation


● Up button provided in app bar
● Controlled by defining parent Activity for child
Activity in the AndroidManifest.xml
This work is licensed under a Creative
Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 4
License.
Back Navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 5
License.
Navigation through history of screens
1. Historys starts from Launcher

2. User clicks the Back button


to navigate to previous screens
in reverse order

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 6
License.
Changing Back button behavior
● Android system manages the back stack and Back button
● If in doubt, don't change
● Only override, if necessary to satisfy user expectation

For example: In an embedded browser, trigger browser's


default back behavior when user presses device Back button

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 7
License.
Overriding onBackPressed()

@Override
public void onBackPressed() {
// Add the Back key handler here.
return;
}

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 8
License.
Hierarchical
Navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 9
License.
Hierarchical navigation patterns
● Parent screen—Screen that enables navigation down to
child screens, such as home screen and main Activity
● Collection sibling—Screen enabling navigation to a
collection of child screens, such as a list of headlines
● Section sibling—Screen with content, such as a story

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 10
License.
Example of a screen hierarchy
1. Parent 1 News App

2. Children: collection siblings


2 Top Stories Tech News Cooking
3. Children: section siblings Headline Headline Headline
Headline Headline Headline
Headline
● Use Activity for parent screen Headline
Headline
Headline
Headline Headline
● Use Activity or Fragment for
children screens
3 Story Story Story

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 11
License.
Types of hierarchical navigation
● Descendant navigation
○ Down from a parent screen to one of its children
○ From a list of headlines—to a story summary—to a story
● Ancestral navigation
○ Up from a child or sibling screen to its parent
○ From a story summary back to the headlines
● Lateral navigation
○ From one sibling to another sibling
○ Swiping between tabbed views
This work is licensed under a Creative
Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 12
License.
Descendant
Navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 13
License.
Descendant navigation
Descendant navigation News App

● Down from a parent screen Top Stories Tech News Cooking


Headline Headline Headline
to one of its children Headline Headline Headline
Headline
● From the main screen to a
Headline Headline
Headline Headline Headline

list of headlines to a story


Story Story Story

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 14
License.
Master/detail flow
● Side-by side on tablets ● Multiple screens on phone

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 15
License.
Controls for descendant navigation
● Navigation drawer
● Buttons, image buttons on main screen
● Other clickable views with text and icons arranged in
horizontal or vertical rows, or as a grid
● List items on collection screens

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 16
License.
Navigation
Drawer

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 17
License.
Navigation drawer

Descendant navigation
1. Icon in app bar
2. Header
3. Menu items

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 18
License.
Layouts for for navigation drawer
Create layouts:
● A navigation drawer as the Activity layout root ViewGroup
● A navigation View for the drawer itself
● An app bar layout that includes room for a navigation icon button
● A content layout for the Activity that displays the navigation drawer
● A layout for the navigation drawer header

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 19
License.
Navigation drawer Activity layout
1. DrawerLayout is root view
2. CoordinatorLayout contains
app bar layout with a Toolbar
3. App content screen layout
3

4. NavigationView with layouts for


header and selectable items
4

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 20
License.
Steps to implement navigation drawer

1. Populate navigation drawer menu with item titles and icons


2. Set up navigation drawer and item listeners in the Activity
code
3. Handle the navigation menu item selections

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 21
License.
Other descendant navigation patterns

● Vertical list, such as RecyclerView


● Vertical grid, such as GridView
● Lateral navigation with a carousel
● Multi-level menus, such as the options menu
● Master/detail navigation flow

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 22
License.
Ancestral
Navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 23
License.
Ancestral navigation (Up button)
● Enable user to go up from a section
or child screen to the parent

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 24
License.
Declare parent of child Activity—AndroidManifest

<activity android:name=".OrderActivity"
android:label="@string/title_activity_order"
android:parentActivityName="com.example.android.
optionsmenuorderactivity.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 25
License.
Lateral
Navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 26
License.
Tabs and swipes
Lateral navigation News App

● Between siblings Top Stories Tech News Cooking


Headline Headline Headline
● From a list of stories to a Headline Headline Headline
Headline Headline Headline
list in a different tab Headline Headline Headline

● From story to story under


the same tab Story Story Story

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 27
License.
Benefits of using tabs and swipes
● A single, initially-selected tab—users
have access to content without further
navigation
● Navigate between related screens
without visiting parent

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 28
License.
Best practices with tabs

● Lay out horizontally


● Run along top of screen
● Persistent across related screens
● Switching should not be treated as history

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 29
License.
Steps for implementing tabs
1. Define the tab layout using TabLayout
2. Implement a Fragment and its layout for each tab
3. Implement a PagerAdapter from FragmentPagerAdapter or
FragmentStatePagerAdapter
4. Create an instance of the tab layout
5. Use PagerAdapter to manage screens (each screen is a Fragment)
6. Set a listener to determine which tab is tapped

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 30
License.
Add tab layout below Toolbar
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 31
License.
Add view pager below TabLayout

<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/tab_layout" />

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 32
License.
Create a tab layout in onCreate()

TabLayout tabLayout = findViewById(R.id.tab_layout);


tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 33
License.
Add the view pager in onCreate()

final ViewPager viewPager = findViewById(R.id.pager);


final PagerAdapter adapter = new PagerAdapter (
getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 34
License.
Add the listener in onCreate()
viewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());}
@Override
public void onTabUnselected(TabLayout.Tab tab) {}
@Override
public void onTabReselected(TabLayout.Tab tab) {} });
This work is licensed under a Creative
Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 35
License.
Learn more
● Navigation Design guide
d.android.com/design/patterns/navigation.html

● Designing effective navigation


d.android.com/training/design-navigation/index.html

● Creating a Navigation Drawer


d.android.com/training/implementing-navigation/nav-drawer.html

● Creating swipe views with tabs


d.android.com/training/implementing-navigation/lateral.html
This work is licensed under a Creative
Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 36
License.
What's Next?

● Concept Chapter: 4.4 User navigation


● Practical: 4.4 User navigation

This work is licensed under a Creative


Android Developer Fundamentals V2 User navigation Commons Attribution 4.0 International 37
License.
END

Android Developer Fundamentals V2 38


Android Developer Fundamentals V2

User Interaction

Lesson 4

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 1
License.
4.4 RecyclerView

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 2
License.
Contents

● RecyclerView Components
● Implementing a RecyclerView

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 3
License.
What is a RecyclerView?
● RecyclerView is scrollable container
for large data sets
● Efficient
○ Uses and reuses limited number of
View elements
○ Updates changing data fast

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 4
License.
RecyclerView
Components

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 5
License.
Components
Overview
● Data
● RecyclerView scrolling list for list items—RecyclerView
● Layout for one item of data—XML file
● Layout manager handles the organization of UI components in a View—
Recyclerview.LayoutManager
● Adapter connects data to the RecyclerView—RecyclerView.Adapter
● ViewHolder has view information for displaying one item—
RecyclerView.ViewHolder

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 6
License.
Components
How components fit together overview

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 7
License.
LayoutisManager
What a layout manager?
● Each ViewGroup has a layout manager
● Use to position View items inside a RecyclerView
● Reuses View items that are no longer visible to the user
● Built-in layout managers
○ LinearLayoutManager
○ GridLayoutManager
○ StaggeredGridLayoutManager
● Extend RecyclerView.LayoutManager
This work is licensed under a Creative
Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 8
License.
Adapter
What is an adapter?
● Helps incompatible interfaces work together
○ Example: Takes data from database Cursor and prepares strings
to put into a View
● Intermediary between data and View
● Manages creating, updating, adding, deleting View items
as underlying data changes
● RecyclerView.Adapter

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 9
License.
Adapter
What is a ViewHolder?
● Used by the adapter to prepare one View with data for one
list item
● Layout specified in an XML resource file
● Can have clickable elements
● Is placed by the layout manager
● RecyclerView.ViewHolder

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 10
License.
Implementing
RecyclerView

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 11
License.
Implementation
Steps Summary
1. Add RecyclerView dependency to build.gradle if needed
2. Add RecyclerView to layout
3. Create XML layout for item
4. Extend RecyclerView.Adapter
5. Extend RecyclerView.ViewHolder
6. In Activity onCreate(), create RecyclerView with
adapter and layout manager
This work is licensed under a Creative
Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 12
License.
app/build.gradle
Add dependency to app/build.gradle
Add RecyclerView dependency to build.gradle if needed:

dependencies {
...
compile 'com.android.support:recyclerview-v7:26.1.0'
...
}

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 13
License.
Activity
Add RecyclerView
layout to XML Layout

<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 14
License.
Item layout
Create layout for 1 list item
<LinearLayout …>
<TextView
android:id="@+id/word"
style="@style/word_title" />
</LinearLayout>

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 15
License.
Adapter: Create
Implement the adapter
public class WordListAdapter
extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {

public WordListAdapter(Context context,


LinkedList<String> wordList) {
mInflater = LayoutInflater.from(context);
this.mWordList = wordList;
}
}
This work is licensed under a Creative
Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 16
License.
Adapter:has
Adapter onCreateViewHolder()
3 required methods

● onCreateViewHolder()
● inBindViewHolder()
● getItemCount()

Let's take a look!


This work is licensed under a Creative
Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 17
License.
Adapter: onCreateViewHolder()
onCreateViewHolder()
@Override
public WordViewHolder onCreateViewHolder(
ViewGroup parent, int viewType) {
// Create view from layout
View mItemView = mInflater.inflate(
R.layout.wordlist_item, parent, false);
return new WordViewHolder(mItemView, this);
}
This work is licensed under a Creative
Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 18
License.
Adapter: onBindViewHolder()
onBindViewHolder()
@Override
public void onBindViewHolder(
WordViewHolder holder, int position) {
// Retrieve the data for that position
String mCurrent = mWordList.get(position);
// Add the data to the view
holder.wordItemView.setText(mCurrent);
}

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 19
License.
Adapter: getItemCount()
getItemCount()

@Override
public int getItemCount() {
// Return the number of data items to display
return mWordList.size();
}

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 20
License.
Adapter:
Create the
ViewHolder
view holder
Class
in adapter class

class WordViewHolder extends RecyclerView.ViewHolder { //.. }

If you want to handle mouse clicks:

class WordViewHolder extends RecyclerView.ViewHolder


implements View.OnClickListener { //.. }

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 21
License.
ViewHolder:
View holder constructor
Constructor
public WordViewHolder(View itemView, WordListAdapter adapter) {
super(itemView);
// Get the layout
wordItemView = itemView.findViewById(R.id.word);
// Associate with this adapter
this.mAdapter = adapter;
// Add click listener, if desired
itemView.setOnClickListener(this);
}
// Implement onClick() if desired
This work is licensed under a Creative
Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 22
License.
Create
Createthe RecyclerView in Activity onCreate()
RecyclerView

mRecyclerView = findViewById(R.id.recyclerview);
mAdapter = new WordListAdapter(this, mWordList);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new
LinearLayoutManager(this));

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 23
License.
Practical: RecyclerView

● This is rather complex with many separate pieces. So,


there is a whole practical where you implement a
RecyclerView that displays a list of clickable words.

● Shows all the steps, one by one with a complete app

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 24
License.
Learn more

● RecyclerView
● RecyclerView class
● RecyclerView.Adapter class
● RecyclerView.ViewHolder class
● RecyclerView.LayoutManager class

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 25
License.
What's Next?

● Concept Chapter: 4.5 RecyclerView


● Practical: 4.5 RecyclerView

This work is licensed under a Creative


Android Developer Fundamentals V2 RecyclerView Commons Attribution 4.0 International 26
License.
END

Android Developer Fundamentals V2 27


Android Developer Fundamentals V2

Delightful User
Experience
Lesson 5

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
and themes
License.
5.1 Drawables, styles,
and themes

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
and themes
License.
Contents

● Drawables
● Creating image assets
● Styles
● Themes

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
and themes
License.
Drawables

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
and themes
License.
Drawables

● Drawable—generic Android class used to represent any


kind of graphic
● All drawables are stored in the res/drawable project folder

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
and themes
License.
Drawable classes

Bitmap File Transition Drawable


Nine-Patch File Vector Drawable
Layer List Drawable … and more
Shape Drawable Custom Drawables
State List Drawable
Level List Drawable

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
and themes
License.
Bitmaps

● PNG (.png), JPG (.jpg), or GIF (.gif) format


● Uncompressed BMP (.bmp)
● WebP (4.0 and higher)
● Creates a BitmapDrawable data type
● Placed directly in res/drawables

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
and themes
License.
Referencing Drawables
● XML: @[package:]drawable/filename
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/myimage" />

● Java code: R.drawable.filename


Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.myimage);

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
and themes
License.
Nine-Patch Files

● Nine-patch files (.9.png) are PNG with stretchable regions


● Only stretches bigger, not smaller, so start with small image
● Often used for backgrounds of UI elements
● Example: button background changes size with label length
● Good intro

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
and themes
License.
Creating Nine-Patch Files

1. Put a small PNG file into res/drawable


2. Right-click and choose Create 9-Patch file
3. Double-click 9-Patch file to open editor
4. Specify the stretchable regions (next slide)

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
and themes
License.
Editing Nine-Patch Files
1. Border to mark stretchable regions for 1
width 7
2
2. Stretchable regions marked for height
3
Pink == both directions
3. Click to turn pixels black. Shift-click 4

(ctrl-click on Mac) to unmark 5


4. Stretchable area
5. Not stretchable
6. Check Show patches
6
7. Preview of stretched image

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
and themes
License.
Layer List
● You can create layered images, just like with drawing tools,
such as Gimp
● In Android, each layer is represented by a drawable
● Layers are organized and managed in XML
● List and the items can have properties
● Layers are drawn on top of each other in the order defined in
the XML file
● LayerDrawable
Drawables, styles This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
and themes
License.
Creating Layer List
<layer-list>
<item>
<bitmap android:src="@drawable/android_red"
android:gravity="center" />
</item>
<item android:top="10dp" android:left="10dp">
<bitmap android:src="@drawable/android_green"
android:gravity="center" />
</item>
<item android:top="20dp" android:left="20dp">
<bitmap android:src="@drawable/android_blue"
android:gravity="center" />
</item>
</layer-list>
Drawables, styles This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
and themes
License.
Shape Drawables & GradientDrawable
● Define a shape and its properties in XML
○ Rectangle, oval, ring, line

● Styled with attributes such as <corners>, <gradient>,


<padding>, <size>, <solid> and <stroke>
See Shape Drawables for more attributes

● Can be inflated for a GradientDrawable

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
and themes
License.
Creating a GradientDrawable
<shape … android:shape="rectangle">
<gradient
android:startColor="@color/white"
android:endColor="@color/blue"
android:angle="45"/>
<corners android:radius="8dp" />
</shape>

Resources res = getResources();


Drawable shape = res.getDrawable(R.drawable.gradient_box);
TextView tv = (TextView)findViewByID(R.id.textview);
tv.setBackground(shape);

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
and themes
License.
Transition Drawables

● Drawable that can cross-fade between two other drawables


● Each graphic represented by <item> inside <selector>
● Represented by TransitionDrawable in Java code
● Transition forward by calling startTransition()
● Transition backward with reverseTransition()

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
and themes
License.
Creating Transition Drawables
<transition ...>
<selector> <item android:drawable="@drawable/on" />
<item android:drawable="@drawable/off" />
</selector>
</transition> <ImageButton
android:id="@+id/button"
android:src="@drawable/transition" />

ImageButton button = findViewById(R.id.button);


TransitionDrawable drawable =
(TransitionDrawable) button.getDrawable();
drawable.startTransition(500);

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
and themes
License.
Vector drawables

● Scale smoothly for all screen sizes


● Android API Level 21 and up
● Use Vector Asset Studio to create (slides below)
● VectorDrawable

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
and themes
License.
Creating Vector drawables
<vector ...
android:height="256dp" android:width="256dp"
android:viewportWidth="32" android:viewportHeight="32">
<path android:fillColor="@color/red"
android:pathData="M20.5,9.5
c-1.955,0,-3.83,1.268,-4.5,3
c-0.67,-1.732,-2.547,-3,-4.5,-3 ... />
</vector>
pathData for heart shape
Drawables, styles This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
and themes
License.
Image Asset
Studio

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
and themes
License.
What is Image Asset Studio?
● Create icons from material icons, images, and text
● Launcher, action bar, tab, notification icons
● Generates a set of icons for generalized screen density
● Stored in /res folder

● To start Image Asset Studio


1. Right-click the res folder of your project
2. Choose New > Image Asset

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
and themes
License.
Using Image Asset Studio
1. Chose icon type
1
and change name 2
2. Choose Image, Clipart, or 3

Text
3. Click icon to chose clipart
4. Inspect assets for 4

multiple screen sizes

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
and themes
License.
Vector Asset
Studio

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
and themes
License.
What is Vector Asset Studio?
● Create icons from material icons or supply your own
vector drawings for API 21 and later
● Launcher, action bar, tab, notification icons
● Generates a scalable vector drawable
● Stored in res folder
● To start Image Asset Studio
1. Right-click res folder of your project
2. Choose New > Vector Asset

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
and themes
License.
Using Image Asset Studio
1. Choose from Material Icon
library, or supply your own 1

SVG or PSD vector drawing 2

2. Opens Material Icon library

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
and themes
License.
Images, memory, and performance
● Use smallest resolution picture necessary
● Resize, crop, compress
● Vector drawings for simple images
● Use Libraries: Glide or Picasso
● Choose appropriate image formats for image type and size
● Use lossy image formats and adjust quality where possible
● Learn about data compression for developers from
Understanding Compression
Drawables, styles This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
and themes
License.
Styles

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
and themes
License.
What is a Style?
● Collection of attributes that define the visual appearance
of a View
● Reduce duplication
● Make code more compact
● Manage visual appearance of many components with one
style

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
and themes
License.
Styles reduce clutter
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#00FF00"
android:typeface="monospace"
android:text="@string/hello" />
<TextView
style="@style/CodeFont"
android:text="@string/hello"
/>

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 29
and themes
License.
Define styles in styles.xml
styles.xml is in res/values

<resources>
<style name="CodeFont">
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 30
and themes
License.
Inheritance: Parent
Define a parent style...
<resources>
<style name="CodeFont">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 31
and themes
License.
Inheritance: Define child
Define child with Codefont as parent

<resources>
<style name="RedCode" parent="@style/Codefont>
<item name="android:textColor">#FF0000</item>
</style>
</resources>

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 32
and themes
License.
Themes

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 33
and themes
License.
Themes
● A Theme is a style applied to an entire activity or even the
entire application
● Themes are applied in AndroidManifest.xml
<application android:theme="@style/AppTheme">

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 34
and themes
License.
Customize AppTheme of Your Project
<!-- Base application theme. -->
<style name="AppTheme"
parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Try: Theme.AppCompat.Light.NoActionBar -->
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
Drawables, styles This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 35
and themes
License.
Styles and Themes Resources
Android platform has collection of built in styles and themes

● Android Styles
● Android Themes
● Styles and Themes Guide
● DayNight Theme Guide

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 36
and themes
License.
Learn more

● Drawable Resource Documentation


● ShapeDrawable
● LinearLayout Guide
● Drawable Resource Guide
● Supported Media formats
● 9-Patch
● Understanding Compression

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 37
and themes
License.
What's Next?

● Concept Chapter: 5.1 Drawables, styles, and themes


● Practical: 5.1 Drawables, styles, and themes

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 38
and themes
License.
END

Drawables, styles This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 39
and themes
License.
Android Developer Fundamentals V2

Delightful User
Experience

Lesson 5

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
Design
License.
5.2 Material Design

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
Design
License.
Contents

● The Material Metaphor ● Motion


● Imagery ● Layout
● Typography ● Components
● Color

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
Design
License.
The Material
Metaphor

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
Design
License.
What is Material Design?

● Design guidelines
● Visual language
● Combine classic principles of good design with
innovation and possibilities of technology and science
● Material Design Spec

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
Design
License.
Material metaphor
● Three-dimensional environment containing
light, material, and shadows
● Surfaces and edges provide visual cues grounded in
reality
● Fundamentals of light, surface, and movement convey
how objects move, interact, and exist in space and in
relation to each other
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
Design
License.
Material design in your app
Elements in your Android app should behave similarly to real
world materials
● Cast shadows
● Occupy space
● Interact with each other

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
Design
License.
Bold, graphic, intentional
● Choose colors deliberately
● Fill screen edge to edge
● Use large-scale typography
● Use white space intentionally
● Emphasize user action
● Make functionality obvious
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
Design
License.
Imagery

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
Design
License.
Imagery

Images help you communicate and differentiate your app

Should be Best practices


● Relevant ● Use together with text
● Informative ● Original images
● Delightful ● Provide point of focus
● Build a narrative
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
Design
License.
Typography

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
Design
License.
Roboto typeface
Roboto is the standard typeface on Android
Roboto has 6 weights
● Thin
● Light
● Regular
● Medium
● Bold
● Black
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
Design
License.
Font styles and scale
● Too many sizes is confusing Display 4

and looks bad Display 3

● Limited set of sizes that Display 2


Display 1
work well together Headline
Title
Subheading
Body 2
Body 1
Caption
Button

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
Design
License.
Setting text appearance

android:textAppearance=
"@style/TextAppearance.AppCompat.Display3"

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
Design
License.
Fonts as resources

● Bundle fonts as resources in app package (APK)


● Create font folder within res, add font XML file to font
● To access font resource:
○ @font/myfont
○ R.font.myfont
● Android 8.0 (API level 26) — Android 4.1 (API level 16) and
higher, use the Support Library 26
● See Fonts in XML
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
Design
License.
Downloadable fonts

● Download fonts from provider app


○ Reduces APK size
○ Increases the app installation success rate
○ Improves the overall system health, saves cellular data, phone
memory, and disk space
● Android 8.0 (API level 26) — API level 14 and higher, use
Support Library 26
● See Downloadable Fonts
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
Design
License.
Color

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
Design
License.
Color

● Bold hues
● Muted environments
● Deep shadows
● Bright highlights

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
Design
License.
Color palette

Material Design recommends using


● a primary color
● along with some shades
● and an accent color
Create a bold user experience for your app
● Material Design Color Palette

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
Design
License.
Color palette for your project

● Android Studio creates a color palette for you


● AppTheme definition in styles.xml
○ colorPrimary—AppBar, branding
○ colorPrimaryDark—status bar, contrast
○ colorAccent—draw user attention, switches, FAB

● Colors defined in colors.xml


● Color selection tool
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
Design
License.
Text color and contrast
Good choice
● Contrast for visual separation
● Contrast for readability
Good choice

● Contrast for accessibility Bad choice

● Not all people see colors the same Bad choice

● Theme handles text by default Bad choice

○ Theme.AppCompat.Light—text will be near black Good choice

○ Theme.AppCompat.Light.DarkActionBar—text near white


Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
Design
License.
Motion

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
Design
License.
Motion
Motion in Material Design Motion is
describes ● Responsive
● Spatial relationships ● Natural
● Functionality ● Aware
● Intention ● Intentional

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
Design
License.
Motion in your app
● Maintain continuity
● Highlight elements or actions
Touch feedback
● Transition naturally between actions
Responsive interaction
or states
● Draw focus
● Organize transitions
● Responsive feedback
Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
Design
License.
Layout

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
Design
License.
Layout for Material Design
● Density independent pixels for views—dp
● Scalable pixels for text—sp
● Elements align to a grid with consistent spacing
● Plan your layout
● Use templates for common layout patterns

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
Design
License.
Layout planning

Spacing Grid alignment Sizing


Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
Design
License.
Components

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
Design
License.
Components
Material Design has guidelines on the use and implementation
of Android components
● Bottom Navigation ● Sliders
● Buttons ● Snackbar
● Cards ● Toasts
● Chips ● Steppers
● Data Tables ● Subheaders
● Dialogs ● Text Fields
● Dividers ● Toolbars

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 29
Design
License.
More components

● Expansion Panels
● Grid Lists
● Lists
● Menus
● Pickers
● Progress Bars
● Selection Controls

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 30
Design
License.
Consistency helps user intuition
FAB

Tabs

Snackbar Navigation Drawer


Material This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 31
Design
License.
Learn more

● Material Design Guidelines ● Cards and Lists Guide


● Floating Action Button
● Material Design Guide
Reference
● Material Design for Android ● Defining Custom
● Material Design for Developers Animations
● View Animation
● Material Palette Generator

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 32
Design
License.
What's Next?

● Concept Chapter: 5.2 Material Design


● Practical: 5.2 Cards, and colors

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 33
Design
License.
END

Material This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 34
Design
License.
Android Developer Fundamentals V2

Delightful User
Experience

Lesson 5

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
adaptive layouts
License.
5.3 Adaptive layouts and
resources

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
adaptive layouts
License.
Contents

● Adaptive layouts and resources


● Alternative resources
● Default resources

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
adaptive layouts
License.
Adaptive
layouts and
resources

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
adaptive layouts
License.
What are adaptive layouts?
Layouts that look good on different
screen sizes, orientations,
and devices

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
adaptive layouts
License.
Adaptive layout
● Layout adapts to configuration
○ Screen size
○ Device orientation
○ Locale
○ Version of Android installed
● Provides alternative resources
○ Localized strings
● Uses flexible layouts
○ GridLayout

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
adaptive layouts
License.
Resource folders of a small app
MyProject/
src/
Put resources in your
res/
drawable/ project's res folder
graphic.png
layout/
activity_main.xml
list_iteminfo.xml
mipmap/
ic_launcher_icon.png
values/
strings.xml

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
adaptive layouts
License.
Common resource directories

● drawable/, layout/, menu/


● values/—XML files of simple values, such as string or color
● xml/—arbitrary XML files
● raw/—arbitrary files in their raw form
● mipmap/—drawables for different launcher icon densities
● Complete list
Resources for This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
adaptive layouts
License.
Alternative
resources

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
adaptive layouts
License.
What are alternative resources?
Different device configurations may require different resources
● Localized strings
● Image resolutions
● Layout dimensions

Android loads appropriate resources automatically

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
adaptive layouts
License.
Create alternative resource folders

Use alternative folders


for resources for
different device
configurations

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
adaptive layouts
License.
Names for alternative resource folders
Resource folder names have the format
resources name-config qualifier

drawable-hdpi drawables for high-density displays


layout-land layout for landscape orientation
layout-v7 layout for version of platform
values-fr all values files for French locale

List of directories and qualifiers and usage detail


Resources for This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
adaptive layouts
License.
Screen Orientation

● Use res/layout and provide alternatives for landscape


where necessary
○ res/layout-port for portrait-specific layouts
○ res/layout-land for landscape specific layouts

● Avoid hard-coded dimensions to reduce need for


specialized layouts

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
adaptive layouts
License.
Simple adaptive layout
GridLayout
● In values/integer.xml:
<integer name="grid_column_count">1</integer>
● In values/integer.xml-land:
<integer name="grid_column_count">2</integer>

Landscape Portrait
Resources for This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
adaptive layouts
License.
Smallest width

● Smallest-width (sw) in folder name specifies minimum


device width
○ res/values-swndp, where n is the smallest width
○ Example: res/values-sw600dp/dimens.xml
○ Does not change with orientation

● Android uses resource closest to (without exceeding)


the device's smallest width
Resources for This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
adaptive layouts
License.
Platform Version

● API level supported by device


○ res/drawables-v14
contains drawables for devices that support API level 14 and above

● Some resources are only available for newer versions


○ WebP image format requires API level 14 (Android 4.0)

● Android API level

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
adaptive layouts
License.
Localization
● Provide strings (and other resources) for specific locales
○ res/values-es/strings.xml
● Increases potential audience for your app
● Locale is based on device's settings
● Localization

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
adaptive layouts
License.
Default
resources

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
adaptive layouts
License.
Default Resources

● Always provide default resources


○ directory name without a qualifier
○ res/layout, res/values, res/drawables….
● Android falls back on default resources when no specific
resources match configuration
● Localizing with Resources

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
adaptive layouts
License.
Learn more

● Supporting Multiple Screens


● Providing Resource
● Providing Resources Guide
● Resources Overview
● Localization Guide

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
adaptive layouts
License.
What's Next?

● Concept Chapter: 5.3 Resources for adaptive layouts


● Practical: 5.3 Adaptive layouts

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
adaptive layouts
License.
END

Resources for This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
adaptive layouts
License.
Android Developer Fundamentals V2

Testing your UI

Lesson 6

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 1
License.
6.1 UI testing

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 2
License.
Contents
● UI testing overview
● Test environment and Espresso setup
● Creating Espresso tests
● Espresso test examples
● Recording tests

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 3
License.
UI testing
overview

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 4
License.
UI testing
● Perform all user UI actions with View elements
○ Tap a View, and enter data or make a choice
○ Examine the values of the properties of each View

● Provide input to all View elements


○ Try invalid values

● Check returned output


○ Correct or expected values?
○ Correct presentation?

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 5
License.
Problems with testing manually

● Time consuming, tedious, error-prone


● UI may change and need frequent retesting
● Some paths fail over time
● As app gets more complex, possible sequences of
actions may grow non-linearly

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 6
License.
Benefits of testing automatically

● Free your time and resources for other work


● Faster than manual testing
● Repeatable
● Run tests for different device states and configurations

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 7
License.
Espresso for single app testing

● Verify that the UI behaves as expected


● Check that the app returns the correct UI output in
response to user interactions
● Navigation and controls behave correctly
● App responds correctly to mocked-out dependencies

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 8
License.
UI Automator for multiple apps
● Verify that interactions between different user apps and
system apps behave as expected
● Interact with visible elements on a device
● Monitor interactions between app and system
● Simulate user interactions
● Requires instrumentation

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 9
License.
What is instrumentation?

● A set of hooks in the Android system


● Loads test package and app into same process, allowing
tests to call methods and examine fields
● Control components independently of app’s lifecycle
● Control how Android loads apps

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 10
License.
Benefits of instrumentation

● Tests can monitor all interaction with Android system


● Tests can invoke methods in the app
● Tests can modify and examine fields in the app
independent of the app’s lifecycle

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 11
License.
Test
environment
And Espresso
setup

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 12
License.
Install Android Support Library

1. In Android Studio choose Tools > Android > SDK Manager


2. Click SDK Tools and look for Android Support Repository
3. If necessary, update or install the library

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 13
License.
Add dependencies to build.gradle

● Android Studio templates include dependencies


● If needed, add the following dependencies:

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation
'com.android.support.test.espresso:espresso-core:3.0.1'

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 14
License.
Add defaultConfig to build.gradle

● Android Studio templates include defaultConfig setting


● If needed, add the following to defaultConfig section:

testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 15
License.
Prepare your device
1. Turn on USB Debugging
2. Turn off all animations in Developer Options > Drawing
○ Window animation scale
○ Transition animation scale
○ Animator duration scale

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 16
License.
Create tests

● Store in module-name/src/androidTests/java/
○ In Android Studio: app > java > module-name (androidTest)

● Create tests as JUnit classes

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 17
License.
Creating
Espresso tests

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 18
License.
Test class definition

@RunWith(AndroidJUnit4.class) — Required annotation for tests


@LargeTest — Based on resources the test uses and time to run
public class ChangeTextBehaviorTest {}

@SmallTest — Runs in < 60s and uses no external resources


@MediumTest — Runs in < 300s, only local network
@LargeTest — Runs for a long time and uses many resources

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 19
License.
@Rule specifies the context of testing

@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);

@ActivityTestRule — Testing support for a single specified activity


@ServiceTestRule — Testing support for starting, binding, shutting down a
service

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 20
License.
@Before and @After set up and tear down

@Before
public void initValidString() {
mStringToBetyped = "Espresso";
}

@Before — Setup, initializations


@After — Teardown, freeing resources

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 21
License.
@Test method structure

@Test
public void changeText_sameActivity() {
// 1. Find a View
// 2. Perform an action
// 3. Verify action was taken, assert result
}

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 22
License.
"Hamcrest" simplifies tests
● “Hamcrest” an anagram of “Matchers”
● Framework for creating custom matchers and assertions
● Match rules defined declaratively
● Enables precise testing
● The Hamcrest Tutorial

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 23
License.
Hamcrest Matchers

● ViewMatcher — find Views by id, content, focus, hierarchy


● ViewAction — perform an action on a view
● ViewAssertion — assert state and verify the result

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 24
License.
Basic example test
@Test
public void changeText_sameActivity() {
// 1. Find view by Id
onView(withId(R.id.editTextUserInput))
// 2. Perform action—type string and click button
.perform(typeText(mStringToBetyped), closeSoftKeyboard());
onView(withId(R.id.changeTextBt)).perform(click());
// 3. Check that the text was changed
onView(withId(R.id.textToBeChanged))
.check(matches(withText(mStringToBetyped)));
}
This work is licensed under a Creative
Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 25
License.
Finding views with onView
● withId() — find a view with the specified Android id
○ onView(withId(R.id.editTextUserInput))
● withText() — find a view with specific text
● allOf() — find a view to that matches multiple conditions
● Example: Find a visible list item with the given text:
onView(allOf(withId(R.id.word),
withText("Clicked! Word 15"),
isDisplayed()))
This work is licensed under a Creative
Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 26
License.
onView returns ViewInteraction object
● If you need to reuse the View returned by onView
● Make code more readable or explicit
● check() and perform() methods

ViewInteraction textView = onView(


allOf(withId(R.id.word), withText("Clicked! Word 15"),
isDisplayed()));
textView.check(matches(withText("Clicked! Word 15")));

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 27
License.
Perform actions
● Perform an action on the View found by a ViewMatcher
● Can be any action you can perform on the View
// 1. Find view by Id
onView(withId(R.id.editTextUserInput))
// 2. Perform action—type string and click button
.perform(typeText(mStringToBetyped), closeSoftKeyboard());
onView(withId(R.id.changeTextBt)).perform(click());

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 28
License.
Check result

● Asserts or checks the state of the View

// 3. Check that the text was changed


onView(withId(R.id.textToBeChanged))
.check(matches(withText(mStringToBetyped)));

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 29
License.
When a test fails
Test
onView(withId(R.id.text_message))
.check(matches(withText("This is a failing test.")));

Result snippet
android.support.test.espresso.base.DefaultFailureHandler$Assertion
FailedWithCauseError: 'with text: is "This is a failing test."'
doesn't match the selected view.
Expected: with text: is "This is a failing test."
Got: "AppCompatTextView{id=2131427417, res-name=text_message ...

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 30
License.
Recording
tests

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 31
License.
Recording an Espresso test
● Use app normally, clicking through the UI
● Editable test code generated automatically
● Add assertions to check if a view holds a certain value
● Record multiple interactions in one session, or record
multiple sessions

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 32
License.
Start recording an Espresso test
1. Run > Record Espresso Test
2. Click Restart app, select target,
and click OK
3. Interact with the app to do what
you want to test

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 33
License.
Add assertion to Espresso test recording

4. Click Add Assertion and select a


UI element
5. Choose text is and enter the
text you expect to see
6. Click Save Assertion and click
Complete Recording

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 34
License.
Learn more from developer docs
Android Studio Documentation Android Developer Documentation
● Best Practices for Testing
● Test Your App
● Getting Started with Testing
● Espresso basics ● Testing UI for a Single App
● Espresso cheat sheet ● Building Instrumented Unit Tests
● Espresso Advanced Samples
● The Hamcrest Tutorial
● Hamcrest API and Utility Classes
● Test Support APIs

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 35
License.
Learn even more

Android Testing Support Library


● Espresso documentation
● Espresso Samples

Videos
● Android Testing Support - Android Testing Patterns #1 (introduction)
● Android Testing Support - Android Testing Patterns #2 (onView view matching)
● Android Testing Support - Android Testing Patterns #3 (onData & adapter views)

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 36
License.
Learn even more

● Google Testing Blog: Android UI Automated Testing


● Atomic Object: “Espresso – Testing RecyclerViews at Specific Positions”
● Stack Overflow: “How to assert inside a RecyclerView in Espresso?”
● GitHub: Android Testing Samples
● Google Codelabs: Android Testing Codelab

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 37
License.
What's Next?

● Concept Chapter: 6.1 UI testing


● Practical: 6.1 Espresso for UI testing

This work is licensed under a Creative


Android Developer Fundamentals V2 UI testing Commons Attribution 4.0 International 38
License.
END

Android Developer Fundamentals V2 39


Android Developer Fundamentals V2

Background
Tasks

Lesson 7

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 1
License.
7.1 AsyncTask
and
AsyncTaskLoader

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 2
License.
Contents

● Threads
● AsyncTask
● Loaders
● AsyncTaskLoader

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 3
License.
Threads

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 4
License.
The main thread

● Independent path of execution in a running program


● Code is executed line by line
● App runs on Java thread called "main" or "UI thread"
● Draws UI on the screen
● Responds to user actions by handling UI events

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 5
License.
The Main thread must be fast
● Hardware updates screen every 16 milliseconds
● UI thread has 16 ms to do all its work
● If it takes too long, app stutters or hangs
WAI
T

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 6
License.
Users uninstall unresponsive apps
● If the UI waits too long for an
operation to finish, it becomes
unresponsive
● The framework shows an
Application Not Responding
(ANR) dialog

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 7
License.
What is a long running task?
● Network operations
● Long calculations
● Downloading/uploading files
● Processing images
● Loading data

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 8
License.
Background threads
Execute long running tasks on a background thread
Main Thread (UI Thread)
Update UI

● AsyncTask
● The Loader Framework
● Services
Worker Thread Do some work

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 9
License.
Two rules for Android threads

● Do not block the UI thread


○ Complete all work in less than 16 ms for each screen
○ Run slow non-UI work on a non-UI thread

● Do not access the Android UI toolkit from outside


the UI thread
○ Do UI work only on the UI thread

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 10
License.
AsyncTask

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 11
License.
What is AsyncTask?
Use AsyncTask to implement basic background tasks

Main Thread (UI Thread)


onPostExecute()

Worker Thread
doInBackground()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 12
License.
Override two methods

● doInBackground()—runs on a background thread


○ All the work to happen in the background

● onPostExecute()—runs on main thread when work done


○ Process results
○ Publish results to the UI

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 13
License.
AsyncTask helper methods
● onPreExecute()
○ Runs on the main thread
○ Sets up the task

● onProgressUpdate()
○ Runs on the main thread
○ receives calls from publishProgress() from background thread

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 14
License.
AsyncTask helper methods

Main Thread (UI Thread)


onPreExecute() onProgressUpdate() onPostExecute()

Worker Thread publishProgress()

doInBackground()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 15
License.
Creating an AsyncTask
1. Subclass AsyncTask
2. Provide data type sent to doInBackground()
3. Provide data type of progress units for
onProgressUpdate()
4. Provide data type of result for onPostExecute()

private class MyAsyncTask


extends AsyncTask<URL,AsyncTask
Integer,
and
Bitmap> {...} This work is licensed under a Creative
Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 16
License.
MyAsyncTask class definition
private class MyAsyncTask
extends AsyncTask<String, Integer, Bitmap> {...}

doInBackground()
doInBackground()
onProgressUpdate()
doInBackground(
onPostExecute()
● String—could be query, URI for filename
● Integer—percentage completed, steps done
● Bitmap—an image to be displayed
● Use Void if no data passed
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 17
License.
onPreExecute()

protected void onPreExecute() {


// display a progress bar
// show a toast
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 18
License.
doInBackground()

protected Bitmap doInBackground(String... query) {


// Get the bitmap
return bitmap;
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 19
License.
onProgressUpdate()

protected void onProgressUpdate(Integer... progress) {


setProgressPercent(progress[0]);
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 20
License.
onPostExecute()

protected void onPostExecute(Bitmap result) {


// Do something with the bitmap
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 21
License.
Start background work

public void loadImage (View view) {


String query = mEditText.getText().toString();
new MyAsyncTask(query).execute();
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 22
License.
Limitations of AsyncTask
● When device configuration changes, Activity is destroyed
● AsyncTask cannot connect to Activity anymore
● New AsyncTask created for every config change
● Old AsyncTasks stay around
● App may run out of memory or crash

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 23
License.
When to use AsyncTask
● Short or interruptible tasks
● Tasks that do not need to report back to UI or user
● Lower priority tasks that can be left unfinished
● Use AsyncTaskLoader otherwise

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 24
License.
Loaders

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 25
License.
What is a Loader?
● Provides asynchronous loading of data
● Reconnects to Activity after configuration change
● Can monitor changes in data source and deliver new data
● Callbacks implemented in Activity
● Many types of loaders available
○ AsyncTaskLoader, CursorLoader

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 26
License.
Why use loaders?

● Execute tasks OFF the UI thread


● LoaderManager handles configuration changes for you
● Efficiently implemented by the framework
● Users don't have to wait for data to load

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 27
License.
Anatomy
What is a of
LoaderManager?
a Loader

● Manages loader functions via callbacks

● Can manage multiple loaders


○ loader for database data, for AsyncTask data, for internet data…

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 28
License.
Get a loader with initLoader()
● Creates and starts a loader, or reuses an existing one,
including its data
● Use restartLoader() to clear data in existing loader

getLoaderManager().initLoader(Id, args, callback);


getLoaderManager().initLoader(0, null, this);

getSupportLoaderManager().initLoader(0, null, this);

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 29
License.
Implementing
AsyncTaskLoader

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 30
License.
AsyncTaskLoader Overview
AsyncTaskLoader AsyncTask WorkToDo

LoaderManager

Request Receive
Work Result

Activity
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 31
License.
AsyncTask AsyncTaskLoader

doInBackground() loadInBackground()
onPostExecute() onLoadFinished()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 32
License.
Steps for AsyncTaskLoader subclass

1. Subclass AsyncTaskLoader
2. Implement constructor
3. loadInBackground()
4. onStartLoading()

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 33
License.
Subclass AsyncTaskLoader

public static class StringListLoader


extends AsyncTaskLoader<List<String>> {

public StringListLoader(Context context, String queryString) {


super(context);
mQueryString = queryString;
}
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 34
License.
loadInBackground()

public List<String> loadInBackground() {


List<String> data = new ArrayList<String>;
//TODO: Load the data from the network or from a database
return data;
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 35
License.
onStartLoading()
When restartLoader() or initLoader() is called, the
LoaderManager invokes the onStartLoading() callback
● Check for cached data
● Start observing the data source (if needed)
● Call forceLoad() to load the data if there are changes or
no cached data
protected void onStartLoading() { forceLoad(); }
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 36
License.
Implement loader callbacks in Activity
● onCreateLoader() — Create and return a new Loader for
the given ID
● onLoadFinished() — Called when a previously created
loader has finished its load
● onLoaderReset() — Called when a previously created
loader is being reset making its data unavailable

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 37
License.
onCreateLoader()

@Override
public Loader<List<String>> onCreateLoader(int id, Bundle args) {
return new StringListLoader(this,args.getString("queryString"));
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 38
License.
onLoadFinished()

Results of loadInBackground() are passed to


onLoadFinished() where you can display them

public void onLoadFinished(Loader<List<String>> loader,


List<String> data) {
mAdapter.setData(data);
}

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 39
License.
onLoaderReset()
● Only called when loader is destroyed
● Leave blank most of the time

@Override
public void onLoaderReset(final LoaderList<String>> loader) { }

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 40
License.
Get a loader with initLoader()
● In Activity
● Use support library to be compatible with more devices

getSupportLoaderManager().initLoader(0, null, this);

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 41
License.
Learn more
● AsyncTask Reference
● AsyncTaskLoader Reference
● LoaderManager Reference
● Processes and Threads Guide
● Loaders Guide
● UI Thread Performance: Exceed the Android Speed Limit
AsyncTask and This work is licensed under a Creative
Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 42
License.
What's Next?

● Concept Chapter: 7.1 AsyncTask and AsyncTaskLoader


● Practical: 7.1 AsyncTask

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 43
License.
END

AsyncTask and This work is licensed under a Creative


Android Developer Fundamentals V2 AsyncTaskLoader
Commons Attribution 4.0 International 44
License.
Android Developer Fundamentals V2

Background
Tasks
Lesson 7

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
connection
License.
7.2 Internet connection

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
connection
License.
Steps to connect to the Internet
1. Add permissions to Android Manifest
2. Check Network Connection
3. Create Worker Thread
4. Implement background task
a. Create URI
b. Make HTTP Connection
c. Connect and GET Data
5. Process results
a. Parse Results

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
connection
License.
Permissions

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
connection
License.
Permissions in AndroidManifest
Internet
<uses-permission android:name="android.permission.INTERNET"/>

Check Network State


<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"/>

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
connection
License.
Manage
Network
Connection

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
connection
License.
Getting Network information
● ConnectivityManager
○ Answers queries about the state of network connectivity
○ Notifies applications when network connectivity changes
● NetworkInfo
○ Describes status of a network interface of a given type
○ Mobile or Wi-Fi

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
connection
License.
Check if network is available
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) {


// Create background thread to connect and get data
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
connection
License.
Check for WiFi & Mobile
NetworkInfo networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();

networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
connection
License.
Worker Thread

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
connection
License.
Use Worker Thread

● AsyncTask—very short task, or no result returned to UI


● AsyncTaskLoader—for longer tasks, returns result to UI
● Background Service—later chapter

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
connection
License.
Background work

In the background task (for example in doInBackground())


1. Create URI
2. Make HTTP Connection
3. Download Data

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
connection
License.
Create URI

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
connection
License.
URI = Uniform Resource Identifier

String that names or locates a particular resource


● file://
● http:// and https://
● content://

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
connection
License.
Sample URL for Google Books API
https://www.googleapis.com/books/v1/volumes?
q=pride+prejudice&maxResults=5&printType=books

Constants for Parameters


final String BASE_URL =
"https://www.googleapis.com/books/v1/volumes?";
final String QUERY_PARAM = "q";
final String MAX_RESULTS = "maxResults";
final String PRINT_TYPE = "printType";
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
connection
License.
Build a URI for the request

Uri builtURI = Uri.parse(BASE_URL).buildUpon()


.appendQueryParameter(QUERY_PARAM, "pride+prejudice")
.appendQueryParameter(MAX_RESULTS, "10")
.appendQueryParameter(PRINT_TYPE, "books")
.build();
URL requestURL = new URL(builtURI.toString());

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
connection
License.
HTTP Client
Connection

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
connection
License.
How toa connect
Make connection
to the
from
Internet?
scratch

● Use HttpURLConnection
● Must be done on a separate thread
● Requires InputStreams and try/catch blocks

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
connection
License.
Create a HttpURLConnection

HttpURLConnection conn =
(HttpURLConnection) requestURL.openConnection();

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
connection
License.
Configure connection

conn.setReadTimeout(10000 /* milliseconds */);


conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
connection
License.
Connect and get response
conn.connect();
int response = conn.getResponseCode();

InputStream is = conn.getInputStream();
String contentAsString = convertIsToString(is, len);
return contentAsString;

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
connection
License.
Close connection and stream

} finally {
conn.disconnect();
if (is != null) {
is.close();
}
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
connection
License.
Convert
Response to
String

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
connection
License.
Convert input stream into a string
public String convertIsToString(InputStream stream, int len)
throws IOException, UnsupportedEncodingException {

Reader reader = null;


reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
connection
License.
BufferedReader is more efficient
StringBuilder builder = new StringBuilder();
BufferedReader reader =
new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
if (builder.length() == 0) {
return null;
}
resultString = builder.toString();

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
connection
License.
HTTP Client
Connection
Libraries

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
connection
License.
How toa connect
Make connection
to the
using
Internet?
libraries

● Use a third party library like OkHttp or Volley


● Can be called on the main thread
● Much less code

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
connection
License.
How to connect to the Internet?
Volley
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,


new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {}
});
queue.add(stringRequest);

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
connection
License.
OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, final Response response)
throws IOException {
try {
String responseData = response.body().string();
JSONObject json = new JSONObject(responseData);
final String owner = json.getString("name");
} catch (JSONException e) {}
}
});

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 29
connection
License.
Parse Results

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 30
connection
License.
Parsing the results
● Implement method to receive and handle results
( onPostExecute())
● Response is often JSON or XML
Parse results using helper classes
● JSONObject, JSONArray
● XMLPullParser—parses XML

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 31
connection
License.
JSON basics

{
"population":1,252,000,000,
"country":"India",
"cities":["New Delhi","Mumbai","Kolkata","Chennai"]
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 32
connection
License.
JSONObject basics

JSONObject jsonObject = new JSONObject(response);


String nameOfCountry = (String) jsonObject.get("country");
long population = (Long) jsonObject.get("population");
JSONArray listOfCities = (JSONArray) jsonObject.get("cities");
Iterator<String> iterator = listOfCities.iterator();
while (iterator.hasNext()) {
// do something
}

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 33
connection
License.
Another JSON example
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 34
connection
License.
Another JSON example
Get "onclick" value of the 3rd item in the "menuitem" array

JSONObject data = new JSONObject(responseString);


JSONArray menuItemArray =
data.getJSONArray("menuitem");
JSONObject thirdItem =
menuItemArray.getJSONObject(2);
String onClick = thirdItem.getString("onclick");
Internet This work is licensed under a Creative
Android Developer Fundamentals V2 Commons Attribution 4.0 International 35
connection
License.
Learn more

● Connect to the Network Guide


● Managing Network Usage Guide
● HttpURLConnection reference
● ConnectivityManager reference
● InputStream reference

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 36
connection
License.
What's Next?

● Concept Chapter: 7.2 Internet connection


● Practical: 7.2 AsyncTask and AsyncTaskLoader

Internet This work is licensed under a Creative


Android Developer Fundamentals V2 Commons Attribution 4.0 International 37
connection
License.
END

Android Developer Fundamentals V2 38


Android Developer Fundamentals V2

Background
Tasks

Lesson 7

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 1
License.
7.3 Broadcasts

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 2
License.
Contents

● Broadcasts
● Send a custom broadcasts
● Broadcast receivers
● Implementing broadcast receivers
● Restricting the broadcasts
● Best practices

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 3
License.
Broadcasts

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 4
License.
Broadcast vs. Implicit Intents
Broadcasts
Broadcasts are messages sent by Android system and other
Android apps, when an event of interest occurs.

Broadcasts are wrapped in an Intent object. This Intent


object’s contains the event details such as,
android.intent.action.HEADSET_PLUG, sent when a
wired headset is plugged or unplugged.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 5
License.
Broadcast
Types of broadcasts
vs. Implicit Intents

Types of broadcast:
● System broadcast.
● Custom broadcast.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 6
License.
Broadcast
System broadcasts
vs. Implicit Intents
System broadcast are the messages sent by the Android system, when a
system event occurs, that might affect your app.

Few examples:
● An Intent with action, ACTION_BOOT_COMPLETED is broadcasted
when the device boots.
● An Intent with action, ACTION_POWER_CONNECTED is broadcasted
when the device is connected to the external power.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 7
License.
Broadcast
Custom broadcasts
vs. Implicit Intents

Custom broadcasts are broadcasts that your app sends out, similar to the
Android system.
For example, when you want to let other app(s) know that some data has
been downloaded by your app, and its available for their use.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 8
License.
Send a custom
broadcasts

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 9
License.
Send a custom broadcast

Android provides three ways for sending a broadcast:


● Ordered broadcast.
● Normal broadcast.
● Local broadcast.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 10
License.
Ordered Broadcast
● Ordered broadcast is delivered to one receiver at a time.
● To send a ordered broadcast, use the sendOrderedBroadcast()
method.
● Receivers can propagate result to the next receiver or even abort the
broadcast.
● Control the broadcast order with android:priority attribute in the
manifest file.
● Receivers with same priority run in arbitrary order.
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 11
License.
Normal Broadcast
● Delivered to all the registered receivers at the same time, in an
undefined order.
● Most efficient way to send a broadcast.
● Receivers can’t propagate the results among themselves, and
they can’t abort the broadcast.
● The sendBroadcast() method is used to send a normal
broadcast. This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 12
License.
Local Broadcast
● Sends broadcasts to receivers within your app.
● No security issues since no interprocess communication.
● To send a local broadcast:
○ To get an instance of LocalBroadcastManager.
○ Call sendBroadcast() on the instance.

LocalBroadcastManager.getInstance(this)
.sendBroadcast(customBroadcastIntent);
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 13
License.
Broadcast
Receivers

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 15
License.
What is a broadcast receiver?
● Broadcast receivers are app components.
● They register for various system broadcast and or custom
broadcast.
● They are notified (via an Intent):
○ By the system, when an system event occurs that your
app is registered for.
○ By another app, including your own if your app is
registered for that custom event.
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 16
License.
Register your broadcast receiver
Broadcast receivers can be registered in two ways:
● Static receivers
○ Registered in your AndroidManifest.xml, also called as
Manifest-declared receivers.
● Dynamic receivers
○ Registered using app or activities' context in your Java files,
also called as Context-registered receivers.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 17
License.
Receiving a system broadcast
● Starting from Android 8.0 (API level 26), static receivers can't receive
most of the system broadcasts.
● Use a dynamic receiver to register for these broadcasts.
● If you register for the system broadcasts in the manifest, the
Android system won't deliver them to your app.
● A few broadcasts, are excepted from this restriction. See the
complete list of implicit broadcast exceptions.
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 18
License.
Implementing
Broadcast
Receivers

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 19
License.
To create a broadcast receiver
● Subclass the BroadcastReceiver class and override
its onReceive() method.

● Register the broadcast receiver and specify the intent-


filters:
○ Statically, in the Manifest.
○ Dynamically, with registerReceiver().

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 20
License.
What are Intent-filters
Intent-filters specify the types of intents a broadcast receiver
can receive. They filter the incoming intents based on the
Intent values like action.

To add an intent-filter:
● To your AndroidManifest.xml file, use <intent-
filter> tag.
● To your Java file use the IntentFilter object.
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 21
License.
Subclass a broadcast receiver

In Android studio, File > New > Other > BroadcastReceiver

public class CustomReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
// This method is called when the BroadcastReceiver
// is receiving an Intent broadcast.
throw new UnsupportedOperationException("Not yet implemented");
}
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 22
License.
Implement onReceive()
Example implementation of onReceive() method which handles power
connected and disconnected.
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
switch (intentAction){
case Intent.ACTION_POWER_CONNECTED:
break;
case Intent.ACTION_POWER_DISCONNECTED:
break;
}
} Android Developer Fundamentals V2 Broadcasts
This work is licensed under a Creative
Commons Attribution 4.0 International 23
License.
Register statically in Android manifest
● <receiver> element inside <application> tag.
● <intent-filter> registers receiver for specific intents.
<receiver
android:name=".CustomReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 24
License.
Register dynamically

● Register your receiver in onCreate() or onResume().


// Register the receiver using the activity context.
this.registerReceiver(mReceiver, filter);

● Unregister in onDestroy() or onPause().


// Unregister the receiver
this.unregisterReceiver(mReceiver);

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 25
License.
Register a Local broadcast receiver

Register local receivers dynamically, because


static registration in the manifest is not possible
for a local broadcasts.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 26
License.
Register a Local broadcast receiver
To register a receiver for local broadcasts:
● Get an instance of LocalBroadcastManager.
● Call registerReceiver().

LocalBroadcastManager.getInstance(this).registerReceiver
(mReceiver,
new IntentFilter(CustomReceiver.ACTION_CUSTOM_BROADCAST));

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 27
License.
Unregister a Local broadcast receiver
To unregister a local broadcast receiver:
● Get an instance of the LocalBroadcastManager.
● Call LocalBroadcastManager.unregisterReceiver().

LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mReceiver);

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 28
License.
Restricting
broadcasts

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 29
License.
Restricting broadcasts
● Restricting your broadcast is strongly recommended.
● An unrestricted broadcast can pose a security threat.
● For example: If your apps’ broadcast is not restricted and
includes sensitive information, an app that contains
malware could register and receive your data.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 30
License.
Ways to restrict a broadcast
● If possible, use a LocalBroadcastManager, which
keeps the data inside your app, avoiding security leaks.
● Use the setPackage() method and pass in the package
name. Your broadcast is restricted to apps that match the
specified package name.
● Access permissions can be enforced by sender or receiver.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 31
License.
Enforce permissions by sender
To enforce a permission when sending a broadcast:
● Supply a non-null permission argument to
sendBroadcast().
● Only receivers that request this permission using the
<uses-permission> tag in their
AndroidManifest.xml file can receive the broadcast.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 32
License.
Enforce permissions by receiver

To enforce a permission when receiving a broadcast:


● If you register your receiver dynamically, supply a non-null
permission to registerReceiver().
● If you register your receiver statically, use the
android:permission attribute inside the <receiver>
tag in your AndroidManifest.xml.

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 33
License.
Best practices

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 34
License.
Best practices
● Make sure namespace for intent is unique and you own it.
● Restrict broadcast receivers.
● Other apps can respond to broadcast your app sends —use
permissions to control this.
● Prefer dynamic receivers over static receivers.
● Never perform a long running operation inside your
broadcast receiver.
This work is licensed under a Creative
Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 35
License.
Learn more

● BroadcastReceiver Reference
● Intents and Intent Filters Guide
● LocalBroadcastManager Reference
● Broadcasts overview

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 36
License.
What's Next?

● Concept Chapter: 7.3 Broadcasts


● Practical: 7.3 Broadcast Receivers

This work is licensed under a Creative


Android Developer Fundamentals V2 Broadcasts Commons Attribution 4.0 International 37
License.
END

Android Developer Fundamentals V2 38


Android Developer Fundamentals V2

Background
Tasks
Lesson 7

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 1
License.
7.4 Services

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 2
License.
Contents

● Services for long tasks.


● IntentService

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 3
License.
Services is an advanced topic

● Services are complex.


● Many ways of configuring a service.
● This lesson has introductory information only.
● Explore and learn for yourself if you want to use services.

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 4
License.
Services for
Long Tasks

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 5
License.
What is a service?

A Service is an application component that can perform


long-running operations in the background and does not
provide a user interface.

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 6
License.
What are services good for?

● Network transactions.
● Play music.
● Perform file I/O.
● Interact with a database.

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 7
License.
Characteristics of services

● Started with an Intent.


● Can stay running when user switches applications.
● Lifecycle—which you must manage.
● Other apps can use the service—manage permissions.
● Runs in the main thread of its hosting process.

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 8
License.
Forms of services: started

● Started with startService()


● Runs indefinitely until it stops itself
● Usually does not update the UI

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 9
License.
Forms of services: bound
● Offers a client-server interface that allows
components to interact with the service
● Clients send requests and get results
● Started with bindService()
● Ends when all clients unbind

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 10
License.
Services and threads

Although services are separate from the UI, they still run
on the main thread by default (except IntentService)

Offload CPU-intensive work to a separate thread within


the service

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 11
License.
Updating the app

If the service can't access the UI, how do you update the app
to show the results?

Use a broadcast receiver!

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 12
License.
Foreground services

Runs in the background but requires that the user is actively


aware it exists—e.g. music player using music service
● Higher priority than background services since user will
notice its absence—unlikely to be killed by the system
● Must provide a notification which the user cannot dismiss
while the service is running

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 13
License.
Background services limitations
● Starting from API 26, background app is not allowed to create a
background service.
● A foreground app, can create and run both foreground and background
services.
● When an app goes into the background, the system stops the app's
background services.
● The startService() method now throws an IllegalStateException
if an app is targeting API 26.
● These limitations don't affect foreground services or bound services.
This work is licensed under a Creative
Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 14
License.
Creating a service
● <service android:name=".ExampleService" />
● Manage permissions.
● Subclass IntentService or Service class.
● Implement lifecycle methods.
● Start service from Activity.
● Make sure service is stoppable.
This work is licensed under a Creative
Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 15
License.
Stopping a service

● A started service must manage its own lifecycle


● If not stopped, will keep running and consuming
resources
● The service must stop itself by calling stopSelf()
● Another component can stop it by calling stopService()
● Bound service is destroyed when all clients unbound
● IntentService is destroyed after
Android Developer Fundamentals V2
onHandleIntent() returns
This work is licensed under a Creative
Services
Commons Attribution 4.0 International 16
License.
IntentService

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 17
License.
IntentService

● Simple service with simplified lifecycle


● Uses worker threads to fulfill requests
● Stops itself when done

● Ideal for one long task on a single background thread

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 18
License.
IntentService Limitations

● Cannot interact with the UI


● Can only run one request at a time
● Cannot be interrupted

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 19
License.
IntentService restrictions
● IntentService are subjected to the new restrictions on
background services.
● For the apps targeting API 26, Android Support Library
26.0.0 introduces a new JobIntentService.
● JobIntentService provides the same functionality as
IntentService but uses jobs instead of services.

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 20
License.
IntentService Implementation
public class HelloIntentService extends IntentService {
public HelloIntentService() { super("HelloIntentService");}

@Override
protected void onHandleIntent(Intent intent) {
try {
// Do some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} // When this method returns, IntentService stops the service, as appropriate.
}

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 21
License.
Learn more

● Services overview
● Background Execution Limits

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 22
License.
What's Next?

● Concept Chapter: 7.4 Services


● No practical

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 23
License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 Services Commons Attribution 4.0 International 24
License.
Android Developer Fundamentals V2

Alarms and
Schedulers
Lesson 8

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 1
License.
8.1 Notifications

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 2
License.
Contents

● What are notifications? ● Tap action and action buttons


● Notification channels ● Expanded view notifications
● Creating a notification channel ● Delivering notifications
● Creating notifications ● Managing Notifications

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 3
License.
What Are
Notifications?

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 4
License.
What is a notification?

Message displayed to user outside regular app UI

■ Small icon
■ Title
■ Detail text

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 5
License.
How are notifications used?
● Android issues a notification that appears as
icon on the status bar.
● To see details, user opens the notification
drawer.
● User can view notifications any time in the
notification drawer.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 6
License.
App icon badge
Available only on the devices running Android 8.0 (API level 26) and higher.

● New notifications are displayed as a colored


"badge" (also known as a "notification dot") on
the app icon.

● Users can long-press on an app icon to see the


notifications for that app. Similar to the
notification drawer.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 7
License.
Notification
Channels

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 8
License.
Notification channels

● Used to create a user-customizable channel for each type


of notification to be displayed.
● More than one notification can be grouped in to a channel.
● Set notification behavior like sound, light, vibrate and so on,
applied to all the notifications in that channel.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 9
License.
Notification channels are mandatory
● Notification channels are introduced in Android 8.0 (API
level 26)
● All notifications must be assigned to a channel starting
from Android 8.0 (API level 26), else your notifications will
not be displayed.
● For the apps targeting lower than Android 8.0 (API level
26), no need to implement notification channels.
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 10
License.
Notification channels in Settings
● Notification channels appear as
Categories under App
notifications in the device
Settings.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 11
License.
Creating a
Notification
channel

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 12
License.
Create a Notification channel
● Notification channel instance is created using NotificationChannel
constructor.
● You must specify:
○ An ID that's unique within your package.
○ User visible name of the channel.
○ The importance level for the channel.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


NotificationChannel notificationChannel =
new NotificationChannel(CHANNEL_ID, "Mascot Notification",
NotificationManager.IMPORTANCE_DEFAULT);
This work is licensed under a Creative
} Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 13
License.
Importance level
● Available in Android 8.0 (API level 26) and higher.
● Sets the intrusion level, like the sound and visibility for all
notifications posted in the channel.
● Range from IMPORTANCE_NONE(0) to
IMPORTANCE_HIGH(4).
● To support earlier versions of Android (Lower than API level 26),
set the priority.
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 14
License.
Notification priority
● Determines how the system displays the notification with
respect to other notifications, in Android version Lower
than API level 26.
● Set using the setPriority() method for each
notification.
● Range from PRIORITY_MIN to PRIORITY_MAX.

setPriority(NotificationCompat.PRIORITY_HIGH)
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 15
License.
Importance level and priority constants
Importance (Android 8.0 Priority (Android 7.1
User-visible importance level
and higher) and lower)
Urgent
PRIORITY_HIGH or
Makes a sound and appears as a heads-up IMPORTANCE_HIGH
PRIORITY_MAX
notification
High
IMPORTANCE_DEFAULT PRIORITY_DEFAULT
Makes a sound
Medium
IMPORTANCE_LOW PRIORITY_LOW
No sound
Low
No sound and doesn't appear in the status bar IMPORTANCE_MIN PRIORITY_MIN

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 16
License.
Creating
Notifications

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 17
License.
Creating Notification
● Notification is created using NotificationCompat.Builder class.
● Pass the application context and notification channel ID to the
constructor.
● The NotificationCompat.Builder constructor takes the notification
channel ID, this is only used by Android 8.0 (API level 26) and higher, but
this parameter is ignored by the older versions.

NotificationCompat.Builder mBuilder = new


NotificationCompat.Builder(this, CHANNEL_ID);
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 18
License.
Setting notification contents
1. A small icon, set by setSmallIcon().
This is the only content that's required.
1. A title, set by setContentTitle().
2. The body text, set by
setContentText(). This is the
notification message.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 19
License.
Setting notification contents

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.android_icon)
.setContentTitle("You've been notified!")
.setContentText("This is your notification text.");

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 20
License.
Tap action
and
Action buttons

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 21
License.
Add notification tap action
● Every notification must respond when it is tapped, usually
launching an Activity in your app.
● Set an content intent using setContentIntent() method.
● Pass the Intent wrapped in a PendingIntent object.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 22
License.
Notification action buttons

● Action buttons can perform a variety of actions on behalf


of your app, such as starting a background task, placing a
phone call and so on.
● Starting from Android 7.0 (API level 24) reply to messages
directly from notifications.
● To add an action button, pass a PendingIntent to the
addAction() method.
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 23
License.
Pending intents

● A PendingIntent is a description of an intent and target


action to perform with it.

● Give a PendingIntent to another application to grant it


the right to perform the operation you have specified as if
the other app was yourself.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 24
License.
Methods to create a PendingIntent

To instantiate a PendingIntent, use one of the following


methods:
● PendingIntent.getActivity()
● PendingIntent.getBroadcast()
● PendingIntent.getService()

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 25
License.
PendingIntent method arguments

1. Application context
2. Request code—constant integer id for the pending intent
3. Intent to be delivered
4. PendingIntent flag determines how the system handles
multiple pending intents from same app

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 26
License.
Step 1: Create intent

Intent notificationIntent =
new Intent(this, MainActivity.class);

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 27
License.
Step 2: Create PendingIntent

PendingIntent notificationPendingIntent =
PendingIntent.getActivity(
this,
NOTIFICATION_ID,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 28
License.
Step 3: Add to notification builder

To set tap action to the notification:

.setContentIntent(notificationPendingIntent);

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 29
License.
Add action buttons
● Use NotificationCompat.Builder.addAction()
— pass in icon, caption, PendingIntent

.addAction(R.drawable.ic_color_lens_black_24dp,
"R.string.label",
notificationPendingIntent);

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 30
License.
Expanded
view
notifications

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 31
License.
Expandable notifications
● Notifications in the notification drawer appear in two main
layouts, normal view (which is the default) and expanded
view.
● Expanded view notifications were introduced in Android 4.1.
● Use them sparingly -- they take up more space and
attention.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 32
License.
Big text

● For large-format notifications that


include a lot of text.
● Fits more text than a standard view.
● Use the helper class:
NotificationCompat.BigTextStyle

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 33
License.
Big image

● For large-format notifications that


include a large image attachment.

● Use the helper class:

NotificationCompa.BigPictureStyle

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 34
License.
Media

● For media playback notifications.


● Actions for controlling media
such as music
● Image for album cover
● Use the helper class:
● NotificationCompat.MediaStyle
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 35
License.
Managing
Setting styles
Notifications
To create expandable notification that appear, use one of the
helper classes to set the style using the setStyle() method.
mNotifyBuilder
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(myBitmapImage)
.setBigContentTitle("Notification!"));

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 36
License.
Delivering
Notifications

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 37
License.
Building a Notification
Delivering notifications

● Use the NotificationManager class to deliver


notifications.
○ Create an instance of NotificationManager
○ Call notify() to deliver the notification.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 38
License.
Building a Notification
Instantiate NotificationManager

Call getSystemService(), passing in the NOTIFICATION_SERVICE


constant.

mNotifyManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 39
License.
Building
Send notification
a Notification
● Call notify()to deliver the notification, passing in these
two values:
○ A notification ID, which is used to update or cancel the notification.
○ The NotificationCompat object that you created using the
NotificationCompat.Builder object.

mNotifyManager.notify(NOTIFICATION_ID, myNotification);

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 40
License.
Managing
Notifications

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 41
License.
Managingnotifications
Updating Notifications
1. Update a notification by changing and or adding some of its
content.
2. Issue notification with updated parameters using builder.
3. Call notify() passing in the same notification ID.
● If previous notification is still visible, system updates.
● If previous notification has been dismissed, new
notification is delivered.

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 42
License.
Managing notifications
Canceling Notifications
Notifications remain visible until:
● User dismisses it by swiping or by using "Clear All".
● Calling setAutoCancel() when creating the notification,
removes it from the status bar when the user clicks on it.
● App calls cancel() or cancelAll() on
NotificationManager.

mNotifyManager.cancel(NOTIFICATION_ID);
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 43
License.
Design guidelines
If your app sends too many notifications, users will disable
notifications or uninstall the app.
● Relevant: Whether this information is essential for the user.
● Timely: Notifications need to appear when they are useful.
● Short: Use as few words as possible.
● Give users the power to choose -- Use appropriate
notification channels to categorise your notifications.
This work is licensed under a Creative
Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 44
License.
What's Next?

● Concept Chapter: 8.1 Notifications


● Practical: 8.1 Notifications

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 45
License.
The End

This work is licensed under a Creative


Android Developer Fundamentals V2 Notifications Commons Attribution 4.0 International 46
License.
Android Developer Fundamentals V2

Alarms and
Schedulers

Lesson 8

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 1
License.
8.2 Alarms

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 2
License.
Contents

● What are Alarms


● Alarms Best Practices
● Alarm Manager
● Scheduling Alarms
● More Alarm Considerations

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 3
License.
What Are
Alarms

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarm Manager Commons Attribution 4.0 International 4
License.
What is an alarm in Android?

● Not an actual alarm clock.


● Schedules something to happen at a set time.
● Fire intents at set times or intervals.
● Goes off once or recurring.
● Can be based on a real-time clock or elapsed time.
● App does not need to run for alarm to be active.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 5
License.
How alarms work with components

BroadcastReceiver
BroadcastReceiver
wakes up the app
wakes up
and delivers the
delivers notification
notification.
Activity creates Alarm triggers and
a notification and sends out Intent.
sets an alarm.
App may be
destroyed so….
This work is licensed under a Creative
Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 6
License.
Benefits of alarms

● App does not need to run for alarm to be active.


● Device does not have to be awake.
● Does not use resources until it goes off.
● Use with BroadcastReceiver to start services and other
operations.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 7
License.
Measuring time
● Elapsed Real Time—time since system boot.
○ Independent of time zone and locale.
○ Use for intervals and relative time.
○ Use whenever possible.
○ Elapsed time includes time device was asleep.

● Real Time Clock (RTC)—UTC (wall clock) time.


○ When time of day at locale matter.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 8
License.
Wakeup behavior

● Wakes up device CPU if screen is off.


○ Use only for time critical operations.
○ Can drain battery.

● Does not wake up device.


○ Fires next time device is awake.
○ Is polite.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 9
License.
Types of alarms
Elapsed Real Time Real Time Clock (RTC)—
(ERT)—since system time of day matters
boot
Do not wake ELAPSED_REALTIME RTC
up device

Wake up ELAPSED_REALTIME_W RTC_WAKEUP


AKEUP
This work is licensed under a Creative
Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 10
License.
Alarms Best
Practices

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarm Manager Commons Attribution 4.0 International 11
License.
If everybody syncs at the same time...
Imagine an app with millions of users:
● Server sync operation based on clock time.
● Every instance of app syncs at 11:00 p.m.

Load on the server could result in high latency or even


"denial of service"

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 12
License.
Alarm Best Practices

● Add randomness to network requests on alarms.


● Minimize alarm frequency.
● Use ELAPSED_REALTIME, not clock time, if you can.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 13
License.
Battery
● Minimize waking up the device.
● Use inexact alarms.
○ Android synchronizes multiple inexact repeating alarms and
fires them at the same time.
○ Reduces the drain on the battery.
○ Use setInexactRepeating() instead of setRepeating().

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 14
License.
When not to use an alarm

● Ticks, timeouts, and while app is running—Handler.


● Server sync—SyncAdapter with Cloud Messaging Service.
● Inexact time and resource efficiency—JobScheduler.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 15
License.
AlarmManager

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarm Manager Commons Attribution 4.0 International 16
License.
What is AlarmManager

● AlarmManager provides access to system alarm services.


● Schedules future operation.
● When alarm goes off, registered Intent is broadcast.
● Alarms are retained while device is asleep.
● Firing alarms can wake device.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 17
License.
Get an AlarmManager

AlarmManager alarmManager =
(AlarmManager) getSystemService(ALARM_SERVICE);

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 18
License.
Scheduling
Alarms

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarm Manager Commons Attribution 4.0 International 19
License.
What you need to to schedule an alarm

1. Type of alarm.
2. Time to trigger.
3. Interval for repeating alarms.
4. PendingIntent to deliver at the specified time
(just like notifications).

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 20
License.
Schedule a single alarm

● set()—single, inexact alarm.


● setWindow()—single inexact alarm in window of time.
● setExact()—single exact alarm.

More power saving options AlarmManager API 23+.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 21
License.
Schedule a repeating alarm

● setInexactRepeating()
○ repeating, inexact alarm.

● setRepeating()
○ Prior to API 19, creates a repeating, exact alarm.
○ After API 19, same as setInexactRepeating().

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 22
License.
setInexactRepeating()

setInexactRepeating(
int alarmType,
long triggerAtMillis,
long intervalMillis,
PendingIntent operation)

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 23
License.
Create an inexact alarm

alarmManager.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()
+ AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
notifyPendingIntent);
This work is licensed under a Creative
Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 24
License.
More Alarm
Considerations

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarm Manager Commons Attribution 4.0 International 25
License.
Checking for an existing alarm

boolean alarmExists =
(PendingIntent.getBroadcast(this,
0, notifyIntent,
PendingIntent.FLAG_NO_CREATE) != null);

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 26
License.
Doze and Standby

● Doze—completely stationary, unplugged, and idle device.


● Standby—unplugged device on idle apps.
● Alarms will not fire.
● API 23+.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 27
License.
User visible alarms
● setAlarmClock()
● System UI may display time/icon.
● Precise.
● Works when device is idle.
● App can retrieve next alarm with getNextAlarmClock().
● API 21+.
This work is licensed under a Creative
Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 28
License.
Cancel an alarm

● Call cancel() on the AlarmManager


○ pass in the PendingIntent.

alarmManager.cancel(alarmPendingIntent);

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 29
License.
Alarms and Reboots

● Alarms are cleared when device is off or rebooted.

● Use a BroadcastReceiver registered for the


BOOT_COMPLETED event and set the alarm in the
onReceive() method.

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 30
License.
Learn more

● Schedule Repeating Alarms Guide


● AlarmManager reference
● Choosing an Alarm Blog Post
● Scheduling Alarms Presentation
● Optimizing for Doze and Standby

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 31
License.
What's Next?

● Concept Chapter: 8.2 Alarms


● Practical: 8.2 The Alarm Manager

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarms Commons Attribution 4.0 International 32
License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 Alarm Manager Commons Attribution 4.0 International 33
License.
Android Developer Fundamentals V2

Alarms and
Schedulers

Lesson 8

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 1
transfer License.
8.3 Efficient data transfer
and JobScheduler

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 2
transfer License.
Contents

● Transferring Data Efficiently


● Job Scheduler
○ JobService
○ JobInfo
○ JobScheduler

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 3
transfer License.
Transferring
Data Efficiently

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 4
transfer License.
Transferring data uses resources

● Wireless radio uses battery.


○ Device runs out of battery.
○ Need to let device charge.

● Transferring data uses up data plans.


○ Costing users real money (for free apps…).

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 5
transfer License.
Wireless radio power states

● Full power—Active connection, highest rate data transfer.


● Low power—Intermediate state that uses 50% less power.
● Standby—Minimal energy, no active network connection.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 6
transfer License.
Wireless radio state transitions for 3G

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 7
transfer License.
Bundle network transfers

● For a typical 3G device, every data transfer session,


the radio draws energy for almost 20 seconds.
● Send data for 1s every 18s—radio mostly on full power.
● Send data in bundles of 3s—radio mostly idle.
● Bundle your data transfers.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 8
transfer License.
Bundled vs. unbundled

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 9
transfer License.
Prefetch data
● Download all the data you are likely to need for a given time
period in a single burst, over a single connection, at full
capacity.
● If you guess right, reduces battery cost and latency.
● If you guess wrong, may use more battery and data
bandwidth.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 10
transfer License.
Monitor connectivity state

● Wi-Fi radio uses less battery and has more bandwidth than
wireless radio.
● Use ConnectivityManager to determine which radio is
active and adapt your strategy.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 11
transfer License.
Monitor battery state

● Wait for specific conditions to initiate battery intensive


operation.
● BatteryManager broadcasts all battery and charging
details in a broadcast Intent.
● Use a BroadcastReceiver registered for battery status
actions.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 12
transfer License.
Job Scheduler

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 13
transfer License.
What is Job Scheduler

● Used for intelligent scheduling of background tasks.


● Based on conditions, not a time schedule.
● Much more efficient than AlarmManager.
● Batches tasks together to minimize battery drain.
● API 21+ (not in support library).

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 14
transfer License.
Job Scheduler components

● JobService—Service class where the task is initiated.


● JobInfo—Builder pattern to set the conditions for the task.
● JobScheduler—Schedule and cancel tasks, launch service.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 15
transfer License.
JobService

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 16
transfer License.
JobService

● JobService subclass, implement your task here.


● Override
○ onStartJob()
○ onStopJob()

● Runs on the main thread.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 17
transfer License.
onStartJob()

● Implement work to be done here.


● Called by system when conditions are met.
● Runs on main thread.
● Off-load heavy work to another thread.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 18
transfer License.
When does a returns
onStartJob() JobService
a boolean
finish?

FALSE—Job finished.

TRUE
● Work has been offloaded.
● Must call jobFinished() from the worker thread.
● Pass in JobParams object from onStartJob().

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 19
transfer License.
onStopJob()

● Called if system has determined execution of job must stop.


● … because requirements specified no longer met.
● For example, no longer on Wi-Fi, device not idle anymore.
● Before jobFinished(JobParameters, boolean).
● Return TRUE to reschedule.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 20
transfer License.
Basic JobService code
public class MyJobService extends JobService {
private UpdateAppsAsyncTask updateTask = new UpdateAppsAsyncTask();
@Override
public boolean onStartJob(JobParameters params) {
updateTask.execute(params);
return true; // work has been offloaded
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return true;
}
}
This work is licensed under a Creative
Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 21
transfer License.
Register your JobService

<service
android:name=".NotificationJobService"
android:permission=
"android.permission.BIND_JOB_SERVICE"/>

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 22
transfer License.
JobInfo

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 23
transfer License.
JobInfo

● Set conditions of execution.

● JobInfo.Builder object.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 24
transfer License.
JobInfo builder object
● Arg 1: Job ID
● Arg 2: Service component
● Arg 3: JobService to launch

JobInfo.Builder builder = new JobInfo.Builder(


JOB_ID,
new ComponentName(getPackageName(),
NotificationJobService.class.getName()));

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 25
transfer License.
Setting conditions
setRequiredNetworkType(int networkType)
setBackoffCriteria(long initialBackoffMillis, int backoffPolicy)
setMinimumLatency(long minLatencyMillis)
setOverrideDeadline(long maxExecutionDelayMillis)
setPeriodic(long intervalMillis)
setPersisted(boolean isPersisted)
setRequiresCharging(boolean requiresCharging)
setRequiresDeviceIdle(boolean requiresDeviceIdle)

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 26
transfer License.
setRequiredNetworkType()
setRequiredNetworkType(int networkType)
● NETWORK_TYPE_NONE—Default, no network required.
● NETWORK_TYPE_ANY—Requires network connectivity.
● NETWORK_TYPE_NOT_ROAMING—Requires network connectivity
that is not roaming.
● NETWORK_TYPE_UNMETERED—Requires network connectivity
that is unmetered.
This work is licensed under a Creative
Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 27
transfer License.
setMinimumLatency()

setMinimumLatency(long minLatencyMillis)

● Minimum milliseconds to wait before completing task.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 28
transfer License.
setOverrideDeadline()

setOverrideDeadline(long maxExecutionDelayMillis)

● Maximum milliseconds to wait before running the task,


even if other conditions aren't met.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 29
transfer License.
setPeriodic()

setPeriodic(long intervalMillis)
● Repeats task after a certain amount of time.
● Pass in repetition interval.
● Mutually exclusive with minimum latency and override
deadline conditions.
● Task is not guaranteed to run in the given period.
This work is licensed under a Creative
Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 30
transfer License.
setPersisted()

setPersisted(boolean isPersisted)

● Sets whether the job is persisted across system reboots.


● Pass in True or False.
● Requires RECEIVE_BOOT_COMPLETED permission.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 31
transfer License.
setRequiresCharging()

setRequiresCharging(boolean requiresCharging)

● Whether device must be plugged in.


● Pass in True or False.
● Defaults to False.

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 32
transfer License.
setRequiresDeviceIdle()

setRequiresDeviceIdle(boolean requiresDeviceIdle)
● Whether device must be in idle mode.
● Idle mode is a loose definition by the system, when device is
not in use, and has not been for some time.
● Use for resource-heavy jobs.
● Pass in True or False. Defaults to False.
This work is licensed under a Creative
Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 33
transfer License.
JobInfo code

JobInfo.Builder builder = new JobInfo.Builder(


JOB_ID, new ComponentName(getPackageName(),
NotificationJobService.class.getName()))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresDeviceIdle(true)
.setRequiresCharging(true);
JobInfo myJobInfo = builder.build();

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 34
transfer License.
JobScheduler

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 35
transfer License.
Scheduling the job
1. Obtain a JobScheduler object form the system.
2. Call schedule() on JobScheduler, with JobInfo object.

mScheduler =
(JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
mScheduler.schedule(myJobInfo);

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 36
transfer License.
Resources
● Transferring Data Without Draining the Battery Guide
● Optimizing Downloads for Efficient Network Access Guide
● Modifying your Download Patterns Based on the Connectivity Type Guide
● JobScheduler Reference
● JobService Reference
● JobInfo Reference
● JobInfo.Builder Reference
● JobParameters Reference
● Presentation on Scheduling Tasks

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 37
transfer License.
What's Next?

● Concept Chapter: 8.3 Efficient data transfer


● Practical: 8.3 Job Scheduler

This work is licensed under a Creative


Efficient data
Android Developer Fundamentals V2 Commons Attribution 4.0 International 38
transfer License.
END

Android Developer Fundamentals V2 39


Android Developer Fundamentals V2

Preferences
and settings

Lesson 9

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 1
License.
9.0 Data Storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 2
License.
Contents

● Android File System


● Internal Storage
● External Storage
● SQLite Database
● Other Storage Options

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 3
License.
Storage
Options

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 4
License.
Storing data

● Shared Preferences—Private primitive data in key-value pairs


● Internal Storage—Private data on device memory
● External Storage—Public data on device or external storage
● SQLite Databases—Structured data in a private database
● Content Providers—Store privately and make available publicly

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 5
License.
Storing data beyond Android

● Network Connection—On the web with your own server


● Cloud Backup—Back up app and user data in the cloud
● Firebase Realtime Database—Store and sync data with
NoSQL cloud database across clients in realtime

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 6
License.
Files

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 7
License.
Android File System

● External storage -- Public directories


● Internal storage -- Private directories for just your app

Apps can browse the directory structure


Structure and operations similar to Linux and java.io

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 8
License.
Internal storage
● Always available
● Uses device's filesystem
● Only your app can access files, unless explicitly set to be
readable or writable
● On app uninstall, system removes all app's files from
internal storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 9
License.
External storage

● Not always available, can be removed


● Uses device's file system or physically external storage like
SD card
● World-readable, so any app can read
● On uninstall, system does not remove files private to app

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 10
License.
When to use internal/external storage
Internal is best when
● you want to be sure that neither the user nor other apps can
access your files
External is best for files that
● don't require access restrictions and for
● you want to share with other apps
● you allow the user to access with a computer

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 11
License.
Save user's file in shared storage

● Save new files that the user acquires through your app to a
public directory where other apps can access them and the
user can easily copy them from the device
● Save external files in public directories

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 12
License.
Internal
Storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 13
License.
Internal Storage

● Uses private directories just for your app


● App always has permission to read/write
● Permanent storage directory—getFilesDir()
● Temporary storage directory—getCacheDir()

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 14
License.
Creating a file

File file = new File(


context.getFilesDir(), filename);

Use standard java.io file operators or streams


to interact with files

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 15
License.
External
Storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 16
License.
External Storage
● On device or SD card
● Set permissions in Android Manifest
○ Write permission includes read permission

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
This work is licensed under a Creative
Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 17
License.
Always check availability of storage

public boolean isExternalStorageWritable() {


String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 18
License.
Example external public directories
● DIRECTORY_ALARMS and DIRECTORY_RINGTONES
For audio files to use as alarms and ringtones
● DIRECTORY_DOCUMENTS
For documents that have been created by the user
● DIRECTORY_DOWNLOADS
For files that have been downloaded by the user

developer.android.com/reference/android/os/Environment.html
This work is licensed under a Creative
Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 19
License.
Accessing public external directories
1. Get a path getExternalStoragePublicDirectory()
2. Create file

File path = Environment.getExternalStoragePublicDirectory(


Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 20
License.
How much storage left?
● If there is not enough space, throws IOException
● If you know the size of the file, check against space
○ getFreeSpace()
○ getTotalSpace().
● If you do not know how much space is needed
○ try/catch IOException

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 21
License.
Delete files no longer needed

● External storage
myFile.delete();

● Internal storage
myContext.deleteFile(fileName);

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 22
License.
Do not delete the user's files!
When the user uninstalls your app, your app's private storage
directory and all its contents are deleted
Do not use private storage for content that belongs to the user!
For example
● Photos captured or edited with your app
● Music the user has purchased with your app

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 23
License.
Shared
Preferences
& SQLite
Database

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 24
License.
SQLite Database

● Ideal for repeating or structured data, such as contacts


● Android provides SQL-like database
● Covered in following chapters and practicals
○ SQLite Primer
○ Introduction to SQLite Databases
○ SQLite Data Storage Practical
○ Searching an SQLite Database Practical

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 25
License.
Shared Preferences

● Read and write small amounts of primitive data as


key/value pairs to a file on the device storage

● Covered in later chapter and practical


○ Shared Preferences

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 26
License.
Other Storage
Options

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 27
License.
Use Firebase to store and share data
Store and sync data with the Firebase
cloud database
Data is synced across all clients, and
remains available when your app goes
offline
firebase.google.com/docs/database/

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 28
License.
Firebase Realtime Database

● Connected apps share data


● Hosted in the cloud
● Data is stored as JSON
● Data is synchronized in realtime to
every connected client

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 29
License.
Network Connection

● You can use the network (when it's available) to store and
retrieve data on your own web-based services

● Use classes in the following packages


○ java.net.*
○ android.net.*

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 30
License.
Backing up data

● Auto Backup for 6.0 (API level 23) and higher


● Automatically back up app data to the cloud
● No code required and free
● Customize and configure auto backup for your app
● See Configuring Auto Backup for Apps

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 31
License.
Backup API for Android 5.1 (API level 22)

1. Register for Android Backup Service to get a Backup Service Key


2. Configure Manifest to use Backup Service
3. Create a backup agent by extending the BackupAgentHelper class
4. Request backups when data has changed
More info and sample code: Using the Backup AP and Data Backup

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 32
License.
Learn more about files

● Saving Files
● getExternalFilesDir() documentation and code samples
● getExternalStoragePublicDirectory() documentation and code samples
● java.io.File class
● Oracle's Java I/O Tutorial

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 33
License.
Learn more about backups

● Configuring Auto Backup for Apps


● Using the Backup API
● Data Backup

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 34
License.
What's next?

● Concept Chapter: 9.0 Data Storage


● No practical, this was an overview lecture

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 35
License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 36
License.
Android Developer Fundamentals V2

Preferences
and settings

Lesson 9

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 1
License.
9.1 Shared Preferences

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 2
License.
Contents

● Shared Preferences
● Listening to changes

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 3
License.
What is Shared Preferences?

● Read and write small amounts of primitive data as


key/value pairs to a file on the device storage
● SharedPreference class provides APIs for reading, writing,
and managing this data
● Save data in onPause()
restore in onCreate()
Shared This work is licensed under a Creative
Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 4
License.
Shared Preferences AND
and Saved
SavedInstance
InstanceState
State

● Small number of key/value pairs


● Data is private to the application

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 5
License.
Shared Preferences vs. Saved Instance State

● Persist data across user sessions, ● Preserves state data across


even if app is killed and restarted, or activity instances in same user
device is rebooted session
● Data that should be remembered
● Data that should not be
across sessions, such as a user's
remembered across sessions,
preferred settings or their game
such as the currently selected tab
score
or current state of activity.
● Common use is to store user
● Common use is to recreate state
preferences
after the device has been rotated

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 6
License.
Creating Shared Preferences

● Need only one Shared Preferences file per app


● Name it with package name of your app—unique and easy
to associate with app
● MODE argument for getSharedPreferences() is for
backwards compatibility—use only MODE_PRIVATE to be
secure

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 7
License.
getSharedPreferences()

private String sharedPrefFile =


"com.example.android.hellosharedprefs";
mPreferences =
getSharedPreferences(sharedPrefFile,
MODE_PRIVATE);

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 8
License.
Saving Shared Preferences

● SharedPreferences.Editor interface
● Takes care of all file operations
● put methods overwrite if key exists
● apply() saves asynchronously and safely

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 9
License.
SharedPreferences.Editor
@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor preferencesEditor =
mPreferences.edit();
preferencesEditor.putInt("count", mCount);
preferencesEditor.putInt("color", mCurrentColor);
preferencesEditor.apply();
}
Shared This work is licensed under a Creative
Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 10
License.
Restoring Shared Preferences

● Restore in onCreate() in Activity


● Get methods take two arguments—the key, and the default
value if the key cannot be found
● Use default argument so you do not have to test whether
the preference exists in the file

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 11
License.
Getting data in onCreate()
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
if (savedInstanceState != null) {
mCount = mPreferences.getInt("count", 1);
mShowCount.setText(String.format("%s", mCount));

mCurrentColor = mPreferences.getInt("color", mCurrentColor);


mShowCount.setBackgroundColor(mCurrentColor);

mNewText = mPreferences.getString("text", "");


} else { … }

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 12
License.
Clearing

● Call clear() on the SharedPreferences.Editor and apply


changes

● You can combine calls to put and clear. However, when you
apply(), clear() is always done first, regardless of order!

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 13
License.
clear()

SharedPreferences.Editor preferencesEditor =
mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 14
License.
Listening to
Changes

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 15
License.
Listening to changes
● Implement interface
SharedPreference.OnSharedPreferenceChangeListener
● Register listener with
registerOnSharedPreferenceChangeListener()
● Register and unregister listener in onResume() and
onPause()
● Implement on onSharedPreferenceChanged() callback
Shared This work is licensed under a Creative
Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 16
License.
Interface and callback
public class SettingsActivity extends AppCompatActivity
implements OnSharedPreferenceChangeListener { ...

public void onSharedPreferenceChanged(


SharedPreferences sharedPreferences, String key) {
if (key.equals(MY_KEY)) {
// Do something
}
}
}

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 17
License.
Creating and registering listener

SharedPreferences.OnSharedPreferenceChangeListener listener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(
SharedPreferences prefs, String key) {
// Implement listener here
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 18
License.
You need a STRONG reference to the listener

● When registering the listener the preference manager does


not store a strong reference to the listener
● You must store a strong reference to the listener, or it will
be susceptible to garbage collection
● Keep a reference to the listener in the instance data of an
object that will exist as long as you need the listener

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 19
License.
Practical: HelloSharedPrefs

● Add Shared Preferences to a starter app

● Add a "Reset" button that clears both the


app state and the preferences for the app

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 20
License.
Learn more
● Saving Data
● Storage Options
● Saving Key-Value Sets
● SharedPreferences
● SharedPreferences.Editor
Stackoverflow
● How to use SharedPreferences in Android to store, fetch and edit values
● onSavedInstanceState vs. SharedPreferences

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 21
License.
What's Next?

● Concept Chapter: 9.1 Shared Preferences


● Practical: 9.1 Shared Preferences

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 22
License.
END

Shared This work is licensed under a Creative


Android Developer Fundamentals V2 Preferences
Commons Attribution 4.0 International 23
License.
Android Developer Fundamentals V2

Preferences
and settings
Lesson 9

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 1
License.
9.2 App settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 2
License.
Contents
● What are settings?
● Setting screens
● Implement settings
● Default settings
● Save and retrieve settings
● Respond to changes in settings
● Summaries for settings
● Settings Activity template
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 3
License.
Settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 4
License.
What are app settings?

● Users can set features and behaviors of app


Examples:
○ Home location, defaults units of measurement
○ Notification behavior for specific app

● For values that change infrequently and are relevant to


most users
● If values change often, use options menu or nav drawer
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 5
License.
Example settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 6
License.
Accessing settings
Users access settings
through:
1. Navigation drawer
2. Options menu

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 7
License.
Setting screens

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 8
License.
Organize your settings

● Predictable, manageable number of


options
● 7 or less: arrange according to priority
with most important at top
● 7-15 settings: group related settings
under section dividers

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 9
License.
16+ Settings

● Group into screens


opened from main
Settings screen

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 10
License.
View versus Preference
● Use Preference objects instead of View objects in your
Settings screens
● Design and edit Preference objects in the layout editor just
like you do for View objects

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 11
License.
Define Settings in a Preference Screen
● Define settings in a
preferences screen
● It is like a layout
● define in:
res > xml > preferences.xml

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 12
License.
Preference Screen example
<PreferenceScreen>
<PreferenceCategory
android:title="Flight Preferences">
<CheckBoxPreference
android:title="Wake for meals"
... />
<EditTextPreference
android:title="Favorite city"
.../>
</PreferenceCategory>
</PreferenceScreen>
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 13
License.
Every Preference must have a key
● Every preference must have a key
● Android uses the key to save the setting value
<EditTextPreference
android:title="Favorite city"
android:key="fav_city"
… />
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 14
License.
SwitchPreference
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">

<SwitchPreference
android:defaultValue="true"
android:title="@string/pref_title_social"
android:key="switch"
android:summary="@string/pref_sum_social" />
</PreferenceScreen>

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 15
License.
SwitchPreference attributes

● android:defaultValue—true by default
● android:summary—text underneath setting, for some
settings, should change to reflect value
● android:title—title/name
● android:key—key for storing value in SharedPreferences

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 16
License.
EditTextPreference

<EditTextPreference
android:capitalize="words"
android:inputType="textCapWords"
android:key="user_display_name"
android:maxLines="1"
android:defaultValue="@string/pref_default_display_name"
android:title="@string/pref_title_display_name" />

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 17
License.
ListPreference

<ListPreference
android:defaultValue="-1"
android:key="add_friends_key"
android:entries="@array/pref_example_list_titles"
android:entryValues="@array/pref_example_list_values"
android:title="@string/pref_title_add_friends_to_messages" />

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 18
License.
ListPreference

● Default value of -1 for no choice


● android:entries—Array of labels for radio buttons
● android:entryValues —Array of values radio button

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 19
License.
Preference class

● Preference class provides View for each kind of setting


● associates View with SharedPreferences interface to
store/retrieve the preference data
● Uses key in the Preference to store the setting value

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 20
License.
Preference subclasses

● CheckBoxPreference—list item that shows a checkbox


● ListPreference—opens a dialog with a list of radio buttons
● SwitchPreference—two-state toggleable option
● EditTextPreference—that opens a dialog with an EditText
● RingtonePreference—lets user to choose a ringtone

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 21
License.
Classes for grouping
● PreferenceScreen
○ root of a Preference layout hierarchy
○ at the top of each screen of settings

● PreferenceGroup
○ for a group of settings (Preference objects).

● PreferenceCategory
○ title above a group as a section divider
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 22
License.
Implement
settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 23
License.
Settings UI uses fragments
● Use an Activity with a Fragment to display the Settings
screen
● Use specialized Activity and Fragment subclasses that
handle the work of saving settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 24
License.
Activities and fragments for settings
● Android 3.0 and newer: Lesson
focusses
○ AppCompatActivity with PreferenceFragmentCompat on this!
○ OR use Activity with PreferenceFragment

● Android older than 3.0 (API level 10 and lower):


○ build a special settings activity as an extension of the
PreferenceActivity class (use the template!)

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 25
License.
Steps to implement Settings
For AppCompatActivity with PreferenceFragmentCompat:
● Create the preferences screen
● Create an Activity for the settings
● Create a Fragment for the settings
● Add the preferenceTheme to the AppTheme
● Add code to invoke Settings UI
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 26
License.
Basic Activity template

● Basic Activity template


Includes options menu
● Settings menu item provided for
options menu

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 27
License.
Create a Settings Activity subclass
● Extends AppCompatActivity
● in onCreate() display the settings Fragment:
getSupportFragmentManager()
.beginTransaction()
.replace(android.R.id.content,
new MySettingsFragment())
.commit();
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 28
License.
Settings Activity example
public class MySettingsActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new MySettingsFragment())
.commit();
} This is the
} whole class!

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 29
License.
Create a Settings Fragment subclass
● Extends PreferenceFragmentCompat
● Implement methods:
○ onCreatePreferences() displays the settings
○ setOnPreferenceChangeListener() handles any changes
that need to happen when the user changes a
preference (optional)

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 30
License.
PreferenceFragment

public class MySettingsFragment


extends PreferenceFragmentCompat { …}

● Blank fragments include onCreateView() by default


● Replace onCreateView() with onCreatePreferences()
because this fragment displays a preferences screen

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 31
License.
Settings Fragment example
public class MySettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState,
String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 32
License.
Add PreferenceTheme to app's theme
If using PreferenceFragmentCompat, set preferenceTheme
in styles.xml:
<style name="AppTheme" parent="...">
...
<item name="preferenceTheme">
@style/PreferenceThemeOverlay
</item>

</style>

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 33
License.
Invoke Settings UI
Send the Intent to start the Settings Activity:
● From Options menu, update onOptionItemsSelected()
● From Navigation drawer, update onItemClick() on the
OnItemClickListener given to setOnItemClickListener

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 34
License.
Default
Settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 35
License.
Default settings
● Set default to value most users would choose
○ All contacts
● Use less battery power
○ Bluetooth is off until the user turns it on
● Least risk to security and data loss
○ Archive rather than delete messages
● Interrupt only when important
○ When calls and notifications arrive
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 36
License.
Set default values
● Use android:defaultValue in Preference view in xml:
<EditTextPreference
android:defaultValue="London"
… />
● In onCreate() of MainActivity, save default values.

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 37
License.
Save default values in shared preferences

In onCreate() of MainActivity
PreferenceManager.setDefaultValues(
this, R.xml.preferences, false);
● App context, such as this
● Resource ID of XML resource file with settings
● false only calls method the first time the app starts

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 38
License.
Save and retrieve
settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 39
License.
Saving setting values
● No need to write code to save settings!
● If you use specialized Preference Activity and Fragment,
Android automatically saves setting values in shared
preferences

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 40
License.
Get settings from shared preferences
● In your code, get settings from default shared preferences
● Use key as specified in preference view in xml
SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
String destinationPref =
sharedPref.getString("fav_city", "Jamaica");

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 41
License.
Get settings values from shared preferences

● In preference definition in xml: default setting value


<EditTextPreference is different than
android:defaultValue="London"
android:key="fav_city" /> default value returned by
pref.getString() if key is
● In code, get fav_city setting: not found in shared prefs

String destinationPref =
sharedPref.getString("fav_city", "Jamaica");
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 42
License.
Respond to
changes in
settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 43
License.
Listening to changes

● Display related follow-up settings


● Disable or enable related settings
● Change the summary to reflect current choice
● Act on the setting
For example, if the setting changes the screen background,
then change the background
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 44
License.
Listen for changes to settings
● Define setOnPreferenceChangeListener()
● in onCreatePreferences() in the Settings Fragment

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 45
License.
onCreatePreferences() example
@Override
public void onCreatePreferences(Bundle savedInstanceState,
String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
ListPreference colorPref =
(ListPreference) findPreference("color_pref");
colorPref.setOnPreferenceChangeListener(
// see next slide
// ...);
}
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 46
License.
onPreferenceChangeListener() example
Example: change background color when setting changes
colorPref.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(
Preference preference, Object newValue){
setMyBackgroundColor(newValue);
return true;
}
});
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 47
License.
Summaries for
settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 48
License.
Summaries for true/false values
Set attributes to define
conditional summaries for
preferences that have true/false
values

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 49
License.
Summaries for other settings
For settings that have values other than true/false, update
the summary when the setting value changes
● Set the summary in onPreferenceChangeListener()

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 50
License.
Set summary example
EditTextPreference cityPref = (EditTextPreference)
findPreference("fav_city");
cityPref.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference pref, Object value){
String city = value.toString();
pref.setSummary("Your favorite city is " + city);
return true;
}
});
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 51
License.
Activity
Template

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 52
License.
More complex?

For anything more complex


?
use the Settings Activity template!

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 53
License.
Settings Activity template
● Complex Settings
● Backwards
compatibility Phone
● Customize pre-
populated settings
● Adaptive layout for
phones and tablets Tablet
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 54
License.
Learn more

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 55
License.
Learn more
● Android Studio User Guide
● Settings (coding)
● Preference class
● PreferenceFragment
● Fragment
● SharedPreferences
● Saving Key-Value Sets
● Settings (design)
This work is licensed under a Creative
Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 56
License.
What's Next?

● Concept Chapter: 9.2 App settings


● Practical: 9.2 App settings

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 57
License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 App settings Commons Attribution 4.0 International 58
License.
Android Developer Fundamentals V2

Storing Data
with Room
Lesson 10

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 1
License.
10.0 SQLite Primer

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 2
License.
Contents

● SQLite Database
● Queries

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 3
License.
This is only a refresher

This course assumes that you are familiar with


● Databases in general
● SQL databases in particular
● SQL query language

This chapter is a refresher and quick reference


This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 4
License.
SQLite
Database

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 5
License.
SQL Databases

● Store data in tables of rows and columns (spreadsheet…)


● Field = intersection of a row and column
● Fields contain data, references to other fields, or references
to other tables
● Rows are identified by unique IDs
● Column names are unique per table
This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 6
License.
Tables

WORD_LIST_TABLE
_id word definition
1 "alpha" "first letter"
2 "beta" "second letter"
3 "alpha" "particle"

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 7
License.
SQLite software library
Implements SQL database engine that is
● self-contained (requires no other components)
● serverless (requires no server backend)
● zero-configuration (does not need to be configured for your
application)
● transactional (changes within a single transaction in SQLite
either occur completely or not at all)
This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 8
License.
What is a transaction?
A transaction is a sequence of operations performed as a
single logical unit of work.
A logical unit of work must have four properties
● atomicity
● consistency
● isolation
● durability
This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 9
License.
All or nothing
All changes within a single transaction in SQLite either occur
completely or not at all, even if the act of writing the change
out to the disk is interrupted by
● program crash
● operating system crash
● power failure.

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 10
License.
ACID
● Atomicity—All or no modifications are performed
● Consistency—When transaction has completed, all data is in a
consistent state
● Isolation—Modifications made by concurrent transactions must
be isolated from the modifications made by any other
concurrent transactions
● Durability—After a transaction has completed, its effects are
permanently in place in the system
This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 11
License.
Queries

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 12
License.
SQL basic operations

● Insert rows
● Delete rows
● Update values in rows
● Retrieve rows that meet given criteria

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 13
License.
SQL Query
● SELECT word, description
FROM WORD_LIST_TABLE
WHERE word="alpha"
Generic
● SELECT columns
FROM table
WHERE column="value"
This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 14
License.
SELECT columns FROM table

● SELECT columns
○ Select the columns to return
○ Use * to return all columns

● FROM table—specify the table from which to get results

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 15
License.
WHERE column="value"

● WHERE—keyword for conditions that have to be met

● column="value"—the condition that has to be met


○ common operators: =, LIKE, <, >

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 16
License.
AND, ORDER BY, LIMIT
SELECT _id FROM WORD_LIST_TABLE WHERE word="alpha"
AND definition LIKE "%art%" ORDER BY word DESC LIMIT 1

● AND, OR—connect multiple conditions with logic operators


● ORDER BY—omit for default order, or ASC for ascending,
DESC for descending
● LIMIT—get a limited number of results
This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 17
License.
Sample queries

1 SELECT * FROM Get the whole table


WORD_LIST_TABLE

2 SELECT word, definition Returns


FROM WORD_LIST_TABLE [["alpha", "particle"]]
WHERE _id > 2

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 18
License.
More sample queries
3 SELECT _id FROM Return id of word alpha with
WORD_LIST_TABLE substring "art" in definition
WHERE word="alpha" AND [["3"]]
definition LIKE "%art%"

4 SELECT * FROM Sort in reverse and get first item.


WORD_LIST_TABLE Sorting is by the first column
ORDER BY word DESC (_id)
LIMIT 1 [["3","alpha","particle"]]
This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 19
License.
Last sample query

5 SELECT * FROM Returns 1 item starting at position 2.


WORD_LIST_TABLE Position counting starts at 1 (not
LIMIT 2,1 zero!).
Returns
[["2","beta","second letter"]]

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 20
License.
rawQuery()
String query = "SELECT * FROM WORD_LIST_TABLE";
rawQuery(query, null);

query = "SELECT word, definition FROM


WORD_LIST_TABLE WHERE _id> ? ";

String[] selectionArgs = new String[]{"2"}


rawQuery(query, selectionArgs);

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 21
License.
query()
SELECT * FROM String table = "WORD_LIST_TABLE"
WORD_LIST_TABLE String[] columns = new String[]{"*"};
WHERE word="alpha" String selection = "word = ?"
ORDER BY word ASC String[] selectionArgs = new String[]{"alpha"};
LIMIT 2,1; String groupBy = null;
String having = null;
Returns: String orderBy = "word ASC"
String limit = "2,1"
[["alpha",
"particle"]] query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 22
License.
Cursors
Queries always return a Cursor object
Cursor is an object interface that provides random read-write
access to the result set returned by a database query
⇒ Think of it as a pointer to table rows

You will learn more about cursors in the following chapters


This work is licensed under a Creative
Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 23
License.
Learn more

● SQLite website
● Full description of the Query Language
● SQLite class
● Cursor class

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 24
License.
What's Next?

● Concept Chapter: 10.0 SQLite Primer


● No Practical

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 25
License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 SQLite Primer Commons Attribution 4.0 International 26
License.
Advanced Android Development V2

Storing data
with Room
Lesson 10

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 1
and ViewModel License.
10.1 Room, LiveData, and
ViewModel

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 2
and ViewModel License.
Contents

● Architecture Components ● ViewModel


● Entity ● Repository
● DAO ● LiveData
● Room database ● Lifecycle

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 3
and ViewModel License.
Architecture
Components

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 4
and ViewModel License.
Architecture Components
A set of Android libraries for
structuring your app in a way
that is robust, testable, and
maintainable.

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 5
and ViewModel License.
Architecture Components
● Consist of best architecture practices + libraries
● Encourage recommended app architecture
● A LOT LESS boilerplate code
● Testable because of clear separation
● Fewer dependencies
● Easier to maintain

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 6
and ViewModel License.
Guide to app architecture

developer.android.com/arch

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 7
and ViewModel License.
Overview UI Controller
(activity/fragment)
Displays data and
forwards on UI
events
UI is notified of
changes using
observation LiveData Holds all the data
LiveData
LiveData ViewModel
needed for the UI

Single source of
truth for all app data;
Repository clean API for UI to
communicate with

LiveData RoomDatabase Manages local data


LiveData
Entity
SQLite data source,
using objects
SQLite DAO

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 8
and ViewModel License.
MainActivity NewWordActivity
Observer

WordListAdapter

LiveData<List<Word>> The RoomWordsSample


WordViewModel
app that you build in the
WordRepository practical implements this
Room

Word architecture
WordRoomDatabase

SQLite WordDao

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 9
and ViewModel License.
Room overview

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 10
and ViewModel License.
Room overview

Room is a robust SQL object


mapping library

● Generates SQLite Android code


● Provides a simple API for your
database
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 11
and ViewModel License.
Components of Room
● Entity: Defines schema of database table.
● DAO: Database Access Object
Defines read/write operations for database.
● Database: LiveData RoomDatabase
LiveData
Entity
A database holder.
Used to create or SQLite DAO
connect to database
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 12
and ViewModel License.
Entity

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 13
and ViewModel License.
Entity
● Entity instance = public class Person {
private int uid;
row in a database table private String firstName;
private String lastName;
● Define entities as POJO classes }

● 1 instance = 1 row
● Member variable = column name LiveData RoomDatabase
LiveData
Entity

SQLite DAO

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 14
and ViewModel License.
Entity instance = row in a database table
public class Person {
private int uid;
private String firstName;
private String lastName;
}
uid firstName lastName

12345 Aleks Becker

12346 Jhansi Kumar


This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 15
and ViewModel License.
Annotate entities
@Entity
public class Person {
@PrimaryKey (autoGenerate=true)
private int uid;

@ColumnInfo(name = "first_name")
private String firstName;

@ColumnInfo(name = "last_name")
private String lastName;

// + getters and setters if variables are private.


}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 16
and ViewModel License.
@Entity annotation

@Entity(tableName = "word_table")

● Each @Entity instance represents an entity/row in a table

● Specify the name of the table if different from class name

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 17
and ViewModel License.
@PrimaryKey annotation
@PrimaryKey (autoGenerate=true)

● Entity class must have a field annotated as


primary key

● You can auto-generate unique key for each entity

● See Defining data using Room entities

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 18
and ViewModel License.
@NonNull annotation

@NonNull

● Denotes that a parameter, field, or method


return value can never be null
● Use for mandatory fields
● Primary key must use @NonNull

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 19
and ViewModel License.
@ColumnInfo annotation

first_name last_name
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;

● Specify column name if different from


member variable name

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 20
and ViewModel License.
Getters, setters
Every field that's stored in the database must

● be public

OR

● have a "getter" method

… so that Room can access it


This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 21
and ViewModel License.
Relationships
users table
Use @Relation annotation to id

define related entities name

pet

Queries fetch all the returned


object's relations pets table
id

name

owner

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 22
and ViewModel License.
Many more annotations
For more annotations, see
Room package summary
reference

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 23
and ViewModel License.
Data access
object (DAO)

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 24
and ViewModel License.
Data access object

Use data access objects, or DAOs,


LiveData RoomDatabase
LiveData
to access app data using the Entity

Room persistence library SQLite DAO

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 25
and ViewModel License.
Data access object

● DAO methods provide abstract access to the app's


database
● The data source for these methods are entity objects
● DAO must be interface or abstract class
● Room uses DAO to create a clean API for your code

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 26
and ViewModel License.
Example DAO
@Dao
public interface WordDao {
@Insert
void insert(Word word);
@Update
public void updateWords(Word... words);
}
//... More queries on next slide...
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 27
and ViewModel License.
Example queries

@Query("DELETE FROM word_table")


void deleteAll();

@Query("SELECT * from word_table ORDER BY word ASC")


List<Word> getAllWords();

@Query("SELECT * FROM word_table WHERE word LIKE :word ")


public List<Word> findWord(String word);

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 28
and ViewModel License.
Room database

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 29
and ViewModel License.
Room

● Room is a robust SQL object


mapping library

● Generates SQLite Android code

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 30
and ViewModel License.
Room
● Room works with DAO and
Entities
LiveData RoomDatabase
● Entities define the database
LiveData
Entity

schema SQLite DAO

● DAO provides methods to


access database

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 31
and ViewModel License.
Creating Room database
● Create public abstract class extending RoomDatabase
● Annotate as @Database
● Declare entities for database schema
and set version number

@Database(entities = {Word.class}, version = 1)


public abstract class WordRoomDatabase extends RoomDatabase

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 32
and ViewModel License.
Room class example
Entity
@Database(entities = {Word.class}, version = 1)
defines
public abstract class WordRoomDatabase DB schema
extends RoomDatabase { DAO for
database
public abstract WordDao wordDao();
Create
private static WordRoomDatabase INSTANCE; database as
singleton
// ... create instance here instance
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 33
and ViewModel License.
Use Database builder
● Use Room's database builder to create the database
● Create DB as singleton instance

private static WordRoomDatabase INSTANCE;


INSTANCE = Room.databaseBuilder(...)
.build();
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 34
and ViewModel License.
Specify database class and name
● Specify Room database class and database name
INSTANCE = Room.databaseBuilder(
context,
WordRoomDatabase.class, "word_database")
//...
.build();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 35
and ViewModel License.
Specify onOpen callback
● Specify onOpen callback
INSTANCE = Room.databaseBuilder(
context,
WordRoomDatabase.class, "word_database")
.addCallback(sOnOpenCallback)
//...
.build();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 36
and ViewModel License.
Specify migration strategy
● Specify migration strategy callback
INSTANCE = Room.databaseBuilder(
context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
.addCallback(sOnOpenCallback)
.fallbackToDestructiveMigration()
.build();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 37
and ViewModel License.
Room database creation example
static WordRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
Check if database
synchronized (WordRoomDatabase.class) {
exists before
if (INSTANCE == null) {
creating it
INSTANCE = Room.databaseBuilder(
context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
.addCallback(sOnOpenCallback)
.fallbackToDestructiveMigration()
.build();
}}}
return INSTANCE;
} Room, LiveData,
This work is licensed under a Creative
Android Developer Fundamentals V2
Commons Attribution 4.0 International 38
and ViewModel License.
Initialize DB in onOpen callback
private static RoomDatabase.Callback sOnOpenCallback =
new RoomDatabase.Callback(){
@Override
public void onOpen (@NonNull SupportSQLiteDatabase db){
super.onOpen(db);
initializeData();
}};

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 39
and ViewModel License.
Room caveats

● Compile-time checks of SQLite statements


● Do not run database operations on the main thread
● LiveData automatically runs query asynchronously on a
background thread when needed
● Usually, make your RoomDatabase a singleton

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 40
and ViewModel License.
ViewModel

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 41
and ViewModel License.
ViewModel

● View models are objects that


provide data for UI
components and survive
LiveData
LiveData ViewModel
configuration changes. LiveData

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 42
and ViewModel License.
ViewModel

● Provides data to the UI


● Survives configuration changes
● You can also use a ViewModel to share data between
fragments
● Part of the lifecycle library

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 43
and ViewModel License.
Survives configuration changes

Activity Instance
ViewModel

Activity UI
Rotation Event
Data

Re-created Activity
Instance

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 44
and ViewModel License.
ViewModel serves data
● ViewModel serves data to the UI
● Data can come from Room
database or other sources
● ViewModel's role is to return the
data, it can get help to find or
generate the data

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 45
and ViewModel License.
Best practice to use repository
Recommended best practice:
● Use a repository to do the work to
get the data
● Keeps ViewModel as clean
interface between app and data

Repository is discussed in next section


This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 46
and ViewModel License.
Restaurant analogy

● Customer requests meal ● UI requests data from


from server ViewModel
● Server takes order to ● ViewModel asks
chefs Repository for data
● Chefs prepare meal ● Repository gets data
● Server delivers meal to ● ViewModel returns data
customer to UI
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 47
and ViewModel License.
ViewModel example using repository
public class WordViewModel extends AndroidViewModel {
private WordRepository mRepository;
private LiveData<List<Word>> mAllWords;
// Initialize the repository and the list of words
public WordViewModel (Application application) {
super(application);
mRepository = new WordRepository(application);
mAllWords = mRepository.getAllWords();
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 48
and ViewModel License.
ViewModel example continued
LiveData<List<Word>> getAllWords() {
return mAllWords;
}
public void insert(Word word) {
mRepository.insert(word);
}
public void deleteWord(Word word) {
mRepository.deleteWord(word);
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 49
and ViewModel License.
Do not pass context into ViewModel
● Never pass context into ViewModel instances
● Do not store Activity, Fragment, or View instances or
their Context in the ViewModel
● An Activity can be destroyed and created many times
during the lifecycle of a ViewModel
● If you need application context, inherit from
AndroidViewModel
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 50
and ViewModel License.
ViewModel does not survive app closure
● ViewModel survives configuration changes,
not app shutdown
● ViewModel is not a replacement for
onSaveInstanceState()
(if you are not saving the data with Room)
● See Saving UI States

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 51
and ViewModel License.
Repository

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 52
and ViewModel License.
Repository

● Best practice, not part of


Architecture Components Repository
libraries
● Implement repository to
provide single, clean API to
app data

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 53
and ViewModel License.
Repository fetches or generates data

● Use repository to fetch data in


the background
● Analogy: chefs prepare meals
behind the scenes

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 54
and ViewModel License.
Multiple backends Repository

Dao Network

● Potentially, repository could manage query threads and


allow you to use multiple backends
● Example: in Repository, implement logic for deciding
whether to fetch data from a network or use results
cached in the database

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 55
and ViewModel License.
Repository example
public class WordRepository {
private WordDao mWordDao;
private LiveData<List<Word>> mAllWords;
WordRepository(Application application) {
WordRoomDatabase db = WordRoomDatabase.getDatabase(application);
mWordDao = db.wordDao();
mAllWords = mWordDao.getAllWords();
}
[... more code…]
}
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 56
and ViewModel License.
Get and insert data
LiveData<List<Word>> getAllWords() {
return mAllWords;
}

// Must insert data off the main thread


public void insert (Word word) {
new insertAsyncTask(mWordDao).execute(word);
}

[... more code…]


}

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 57
and ViewModel License.
Insert off main thread
private static class insertAsyncTask extends AsyncTask
<Word, Void, Void> {
private WordDao mAsyncTaskDao;
insertAsyncTask(WordDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final Word... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
} This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 58
and ViewModel License.
LiveData

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 59
and ViewModel License.
LiveData
LiveData is a data holder class
that is aware of lifecycle events.
It keeps a value and allows this
LiveData
LiveData ViewModel
value to be observed. LiveData

Use LiveData to keep your UI


up to date with the latest and
greatest data. This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 60
and ViewModel License.
LiveData

● LiveData is observable data


● Notifies observer when data
changes
● Is lifecycle aware:
knows when device rotates
or app stops

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 61
and ViewModel License.
Use LiveData to keep UI up to date
● Create an observer that
observes the LiveData
● LiveData notifies Observer
objects when the observed data
changes
● Your observer can update the
UI every time the data changes

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 62
and ViewModel License.
Creating LiveData

To make data observable, return it as LiveData:

@Query("SELECT * from word_table)


LiveData<List<Word>> getAllWords();

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 63
and ViewModel License.
Using LiveData with Room

Room generates all the


code to update the
LiveData when the
database is updated

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 64
and ViewModel License.
Passing LiveData through layers

When you pass live data through the layers of your app
architecture, from a Room database to your UI, that data
must be LiveData in all layers:
● DAO
● ViewModel
● Repository

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 65
and ViewModel License.
Passing LiveData through layers
● DAO:
@Query("SELECT * from word_table")
LiveData<List<Word>> getAllWords();
● Repository:
LiveData<List<Word>> mAllWords =
mWordDao.getAllWords();
● ViewModel:
LiveData<List<Word>> mAllWords =
mRepository.getAllWords();
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 66
and ViewModel License.
Observing LiveData

● Create the observer in onCreate() in the Activity


● Override onChanged() in the observer to update the UI
when the data changes

When the LiveData changes, the observer is notified and its


onChanged() is executed

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 67
and ViewModel License.
Observing LiveData: example
final Observer<String> nameObserver =
new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
mNameTextView.setText(newName);
}
};

mModel.getCurrentName().observe(this, nameObserver);
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 68
and ViewModel License.
No memory leaks

● Observers are bound to Lifecycle objects


which are objects that have an Android Lifecycle
● Observers clean up after themselves when their associated
lifecycle is destroyed

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 69
and ViewModel License.
LiveData is always up to date

● If a lifecycle object becomes inactive, it


gets the latest data when it becomes
active again
● Example: an activity in the background
gets the latest data right after it returns
to the foreground

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 70
and ViewModel License.
LiveData handles configuration changes
If an activity or fragment
is re-created due to a
configuration change
such as device rotation,
the activity or fragment
immediately receives the
latest available data

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 71
and ViewModel License.
Share resources

● You can extend a LiveData object using the singleton


pattern, for example for services or a database
● The LiveData object connects to the system service once,
and then any observer that needs the resource can just
watch the LiveData object
● See Extend LiveData

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 72
and ViewModel License.
Lifecycle

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 73
and ViewModel License.
Lifecycle-aware components

Instead of managing lifecycle-dependent


components in the activity's lifecycle methods,
onStart(), onStop(), and so on, you can make
any class react to lifecycle events

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 74
and ViewModel License.
Lifecycle-aware components

● Lifecycle-aware components perform actions in


response to a change in the lifecycle status of
another component
● For example, a listener could start and stop itself in
response to an activity starting and stopping

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 75
and ViewModel License.
Use cases

● Switch between coarse and fine-grained location updates


depending on app visibility
● Stop and start video buffering
● Stop network connectivity when app is in background
● Pause and resume animated drawables

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 76
and ViewModel License.
Lifecycle library

● Import the android.arch.lifecycle package


● Provides classes and interfaces that let you build lifecycle-
aware components that automatically adjust their behavior
based on lifecycle state of activity or fragment
● See Handling Lifecycles with Lifecycle-Aware Components

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 77
and ViewModel License.
LifecycleObserver interface
● LifecycleObserver has an Android lifecycle.
● It does not have any methods, instead, uses
OnLifecycleEvent annotated methods.

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 78
and ViewModel License.
@OnLifecycleEvent
@OnLifecycleEvent indicates life cycle methods

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start() {...}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void start() {...}

See Lifecycle.event reference for more lifecycle events

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 79
and ViewModel License.
POJOs can be life cycle aware
You can make any class In these pictures,
react to lifecycle events
the Toast is
created by a plain
old Java class
when app starts
or device rotates
This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 80
and ViewModel License.
Adding lifecycle awareness to a POJO
public class Aquarium {

// Constructor takes Application and lifecycle


public Aquarium(final Application app,
Lifecycle lifecycle) {
...
}

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 81
and ViewModel License.
Constructor for lifecycle aware POJO
public Aquarium(final Application app, Lifecycle lifecycle) {
// Add a new observer to the lifecycle.
lifecycle.addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void start() {
Toast.makeText(app, "LIGHTS ON", Toast.LENGTH_SHORT).show();
}
});
}

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 82
and ViewModel License.
Creating an instance
public class MainActivity extends AppCompatActivity {
private Aquarium myAquarium;
protected void onCreate(...) {
...
// Create aquarium.
// Pass context and this activity's lifecycle
myAquarium = new Aquarium(this.getApplication(),
getLifecycle());
}
} This work is licensed under a Creative
Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 83
and ViewModel License.
What's next?

● Concept chapter: 10.1 Room, LiveData, and ViewModel


● Practical: 10.1A : Room, LiveData, and ViewModel
● Practical: 10.1B : Room, LiveData, and ViewModel

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 84
and ViewModel License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 Room, LiveData, Commons Attribution 4.0 International 85
and ViewModel License.
Android Developer Fundamentals
Course: Lesson Plan (V2)
Last updated Thu Sep 06 2018
By Jocelyn Becker
Copyright Google LLC 2018

SHARED PUBLICLY

Android Developer Fundamentals (V2) is an instructor-led course created by the Google Developers
Training team. Developers taking the course learn basic Android programming concepts and build a
variety of apps, starting with Hello World and working their way up to apps that use a Room
database.

Each lesson contains a slide deck, a concepts chapter, and in most cases, one or more hands-on
tutorial exercises (also known as codelabs). As developers work through the exercises, they create
apps to practice and perfect the skills they're learning. Some lessons are purely conceptual and do
not have practicals.

The course is offered as an in-person course at selected colleges, facilitated by college faculty. All
instructors are invited to use our materials to run their own courses, in accordance with the Creative
Commons license used in the course. The materials are also available online for self-study by
anyone who is familiar with the Java programming language.

Android Developer Fundamentals prepares developers to take the exam for the Associate Android
Developer certification.

Prerequisites

Developers taking the course must have Java programming experience.

Android Developer Fundamentals is intended for computer science and engineering


undergraduates who have already learned the Java programming language.

Page 1
Total course hours

Concept hours: 31, Codelab hours: 31

Contents

Unit 1 – Get started


Lesson 1. Build your first app
1.0: Introduction to Android
1.1: Your first Android app
1.2: Layouts and resources for the UI
1.3: Text and scrolling views
1.4: Resources to help you learn

Lesson 2. Activities and intents


2.1: Activities and intents
2.2: Activity lifecycle and state
2.3: Implicit intents

Lesson 3. Testing, debugging, and using support libraries


3.1: The Android Studio debugger
3.2: C App testing
3.3: The Android Support Library

Unit 2 – User experience


Lesson 4. User interaction
4.1: Buttons and clickable images
4.2: Input controls
4.3: Menus and pickers
4.4: User navigation
4.5: RecyclerView

Lesson 5. Delightful user experience


5.1: Drawables, styles, and themes
5.2: Material Design
5.3: Resources for adaptive layouts

Lesson 6.Testing your UI


6.1: UI testing

Page 2
Unit 3 – Working in the background
Lesson 7. Background tasks
7.1: AsyncTask and AsyncTaskLoader
7.2: Internet connection
7.3: Broadcast receivers
7.4.0: Services

Lesson 8. Alarms and schedulers


8.1: Notifications
8.2: Alarms
8.3: Efficient data transfer

Unit 4 – Saving user data


Lesson 9. Preferences and settings
9.0: Data storage
9.1: Shared preferences
9.2: App settings

Lesson 10. Storing data with Room


10.0: SQLite primer
10.1: Room, LiveData, and ViewModel

Page 3
Unit 1 – Get started
This unit covers installing Android Studio, understanding project structure, building your
first app, creating activities, testing your apps, and using the Android Support Library.

First, you deploy a simple Hello World app. You go on to create an app with a single activity,
and then you create a multi-screen app that passes data between activities. You also learn
how to use the Android Support Library to provide backward-compatibility with earlier
versions of the Android system for your app.

Lecture hours: 10
Codelab hours: 11

Page 4
Lesson 1. Build your first app
This lesson covers:

- Installing Android Studio.


- Creating an Android app project.
- Deploying the app to an emulator and a device.
Lesson hours:
- Building a layout with UI elements including a scrolling list.
4 hours Concepts (C)
- Learning where and how to get help with building applications.
5 hours Codelabs (P)

1.0: Introduction to Android


Understand the motivation for developing Android apps 0.5 C

1.1: Your first Android app


Understand the development process for building Android apps.

Codelabs

1.1 P Android Studio and Hello World 0.5 C


Build your first Android project and run the Hello World app 1P

1.2: Layouts and resources for the UI


Learn how to add interactive UI elements to your app and understand the
range of UI elements available.

Codelabs

1.2 Part A: Your first interactive UI


Add views in the Constraint Layout editor. Update the UI
dynamically depending on user input.
1.2 Part B: The layout editor 1C
Update your app's layout to perform well in portrait and landscape 1P
mode. Learn how to use different layouts. 1P

1.3: Text and scrolling views 1C


Understand the performance implications of different ways to make content 1P

Page 5
in an app scrollable.

Codelabs

1.3: Text and scrolling views


Learn more about TextViews, and use a scrolling view.

1.4: Resources to help you learn


Understand the ways that developers can learn for themselves.

Codelabs

1.4: Available resources 1C


Practice finding answers and solving problems on your own. 1P

Page 6
Lesson 2. Activities and intents
This lesson covers:

- Activities, which are the major building blocks of your app's user
interface.
- Intents: learn about both implicit and explicit intents which are used to
Lesson hours:
communicate between activities.
3 hours Concepts (C)
- Callback events that perform tasks in each stage of the activity lifecycle.
3 hours Codelabs (P)

2.1: Activities and intents


Understand how to send an explicit intent to start a specific activity.

Codelabs

2.1: Activities and intents 1C


Define new activities and start them by sending an explicit Intent. 1P

2.2: Activity lifecycle and state


Learn about activity lifecycles.

Codelabs

2.2: Activity lifecycle and state 1C


Explore activity lifecycles. 1P

2.3: Implicit intents


Understand how to send an implicit intent to sends a general request for an
activity that can handle the request.

Codelabs

2.3: Implicit intents


Start a new activity by sending an implicit intent that looks for an 1C
activity to handle the request. 1P

Page 7
Lesson 3. Testing, debugging, and using support
libraries
This lesson covers:

- Using the debugger.


- Setting and muting breakpoints.
- Unit testing your code. Lesson hours:
- Using support libraries to ensure your app is backward compatible with 3 hours Concepts (C)
previous versions of Android. 3 hours Codelabs (P)

3.1: The Android Studio debugger


Learn about the Android Studio debugger.

Codelabs

3.1: The debugger 1C


Troubleshoot problems and debug your code. 1P

3.2: C App testing


Overview of Android testing, and you learn about creating and running local
unit tests in Android Studio with JUnit.

Codelabs

3.2: Unit tests 1C


Organize and run unit tests in Android Studio 1P

3.3: The Android Support Library


Learn how to use the Android Support Library to get backward-compatible
versions of new Android features

Codelabs

3.3: Support libraries


Use a compatibility class from the support library to provide 1C
backward-compatibility for your app. 1P

Page 8
Page 9
Unit 2 – User experience
Create adaptive, responsive user interfaces that work across a wide range of devices.
Create engaging, responsive interfaces that use material design principles. Test your app's
user interface.

Lecture hours: 9
Codelab hours: 10

Page 10
Lesson 4. User interaction
This lesson covers:

- Understanding and implementing different navigation paths through


your application.
- Customizing user input methods and controls.
Lesson hours:
- Building responsive navigation.
5 hours Concepts (C)
- Using buttons for navigation.
5 hours Codelabs (P)

4.1: Buttons and clickable images


Learn how to create buttons and clickable images for triggering actions
initiated by the user.

Codelabs

4.1: Clickable images 1C


Use an image as an interactive element to perform an action. 1P

4.2: Input controls


Learn about input controls such as switches, spinners and more.

Codelabs

4.2: Input controls


Show the input keyboard, add radio buttons and a drop down 1C
menu (spinner). 1P

4.3: Menus and pickers


Learn about the types of menus, dialogs and pickers.
Codelabs

4.3: Menus and pickers


Set up the app bar and options menu in your app. Use an alert 1C
dialog and a date picker. 1P

Page 11
4.4: User navigation
Learn about the different ways to enable users to navigate through your app.

Codelabs

4.4: User navigation 1C


Add an Up button to the app bar. Add tabs to your app. 1P

4.5: RecyclerView
Learn about RecyclerView, which displays items in a list in a way that uses
memory efficiently.

Codelabs

4.5: RecyclerView
Display a list of interactive items in a RecyclerView. Use a floating 1C
action button (FAB) to add new items. 1P

Page 12
Lesson 5. Delightful user experience
This lesson covers:

- Using themes and styles.


- Creating responsive user interfaces that use material design principles. Lesson hours:
- Creating layouts that work on different screen sizes and orientations. 3 hours Concepts (C)
- Creating accessible and easily localizable apps. 4 hours Codelabs (P)

5.1: Drawables, styles, and themes


Learn to use drawables, which are compiled images. Learn how styles and
themes can give your app a consistent look with less XML code.

Codelabs

5.1: Drawables, styles, and themes 1C


Add drawables, styles and themes to your app. 1P

5.2: Material Design


Learn about material design, a visual design philosophy that allows apps to
include material design attributes, such as depth and elevation.

Codelabs

5.2: Cards and colors


Apply material design guidelines to lists and cards. Use material 1C
design colors. 1P

5.3: Resources for adaptive layouts


Learn how to create layouts that work well for different screen sizes and
orientations, different devices, different locales and languages, and different
versions of Android.

Codelabs

5.3: Adaptive layouts 1C


Use resource layout folders to allow your app to work well in 1P

Page 13
different orientations and screen sizes.

Lesson 6.Testing your UI


This lesson covers:

- An overview to UI Testing.
- An introduction to the Espresso Framework.
- Manual Testing.
- Automated Testing.
Lesson hours:
- Using Espresso and UI Automator.
1 hours Concepts (C)
- Recording Tests.
1 hours Codelabs (P)

6.1: UI testing
Learn about testing the user interface of your app.

Codelabs

6.1: Espresso for UI testing


Use Espresso, a mechanism for recording user interactions, to test 1C
your app's user interface. 1P

Unit 3 – Working in the background


This unit covers how to do background work, how to schedule tasks, and how to trigger
events. It covers the performance implications of executing work in the background, as well
as best practices for reducing battery drain. You learn how Android determines which apps
to keep running and which to stop when resources run low.

You write an app that connects to the Internet in a background thread to find the author of
any book. You also build apps that send notifications and schedule tasks, and you learn
how to implement scheduling functionality for apps that run on earlier versions of Android.

Lecture hours: 7
Codelab hours: 6

Page 14
Lesson 7. Background tasks
This lesson covers:

- Establishing an internet connection.


- Sending an HTTP request.
- Parsing a JSON response.
- Running work asynchronously in the background.
- Using AsyncTask and AsyncTaskLoader.
Lesson hours:
- Working with Broadcast Receivers.
4 hours Concepts (C)
- Understanding Services.
3 hours Codelabs (P)

7.1: AsyncTask and AsyncTaskLoader


Learn about using AsyncTask to run work in the background so that the user
does not have to wait for the task to complete.

Codelabs

7.1 P AsyncTask 1C
Add an AsyncTask to your app to run a task in the background. 1P

7.2: Internet connection


Learn how to enable your app to connect to the internet.

Codelabs

7.2 P AsyncTask and AsyncTaskLoader


Enable your app to connect to the internet using an AsyncTask, then
update it to use an AsyncTaskLoader so that the task keeps running 1C
if the user changes their device's orientation. 1P

7.3: Broadcast receivers


Learn about how to send and process broadcasts.

Codelabs
1C
7.3: Broadcast receivers 1P

Page 15
Responds to a system broadcast.Send and receive a custom
broadcast.

7.4.0: Services
Learn about the different types of services, how to use them, and how to
manage their lifecycles within your app. 1C

Lesson 8. Alarms and schedulers


This lesson covers:

- Scheduling and triggering background tasks.


- Using alarms.
- Understanding the impact of data transfer on battery power and
Lesson hours:
performance.
3 hours Concepts (C)
- Working with Job Scheduler.
3 hours Codelabs (P)

Page 16
8.1: Notifications
Learn how to create, deliver, and reuse notifications.

Codelabs

8.1: Notifications 1C
Send and update a notification. 1P

8.2: Alarms
Learn how to schedule alarms.

Codelabs

8.2: The alarm manager 1C


Schedule and cancel an alarm. 1P

8.3: Efficient data transfer


Learn how data transfer can drain your users' batteries, and learn strategies
for minimizing battery drain.

Codelabs

8.3: JobScheduler
Use JobScheduler to schedule tasks in a way that reduces battery 1C
drain. 1P

Page 17
Unit 4 – Saving user data
This unit discusses how to store user data. You learn how to use shared preferences to
save simple key value pairs, then you learn how to use the Room database to save,
retrieve, and update user data. This unit also introduces you to the Android Architecture
Components, which represent best practices for structuring your app.

Lecture hours: 5
Codelab hours: 4

Page 18
Lesson 9. Preferences and settings
This lesson covers:

- ways to save data


- using Shared Preferences as a way to save data
Lesson hours:
- using the Settings activity to provide an interface that allowins users to
3 hours Concepts (C)
set and save app settings
2 hours Codelabs (P)

9.0: Data storage


Learn the different ways to store data in your app. 1C

9.1: Shared preferences


Learn when and how to use SharedPreferences to save data as key-value
pairs.

Codelabs

9.1: Shared preferences 1C


Use SharedPreferences to save and retrieve user preferences. 1P

9.2: App settings


Learn how to allow users to update and save app settings.

Codelabs

9.2 P App settings


Add a settings activity to an app to save the user's preferred app 1C
settings. 1P

Page 19
Lesson 10. Storing data with Room
This lesson covers:

- intro to SQLite
- Architecture Components
Lesson hours:
- using Room Database, ViewModel and Repository to save and manage
2 hours Concepts (C)
data in your app
2 hours Codelabs (P)

10.0: SQLite primer


Refresher and quick reference to interacting with an SQLlite relational
database management system. Android provides a builtin SQLite database. 1C

10.1: Room, LiveData, and ViewModel


Introduction to Architecture Components, which provides guidelines and
libraries to help you implement best practices in app architecture.

Codelabs

10.1 Part A: Room, LiveData, and ViewModel


Use Android's Room database to save and retrieve data in the
database. Use ViewModel and Repository to learn best practices.
1C
10.1 Part B: Room, LiveData, and ViewModel 1P
Delete and update items in a Room database. 1P

That's all folks! THE END

Page 20

You might also like