You are on page 1of 139

Introduction to Android

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 1
Android
4.0 International License
Android Ecosystem

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 2
Android
4.0 International 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 Commons Attribution-NonCommercial 3
Android
4.0 International 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 Commons Attribution-NonCommercial 4
Android
4.0 International 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 Commons Attribution-NonCommercial 5
Android
4.0 International 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 Commons Attribution-NonCommercial 6
Android
4.0 International License
Android app examples

Pandora Pokemon GO Facebook


Messenger
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 7
Android
4.0 International 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 Commons Attribution-NonCommercial 8
Android
4.0 International 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 Commons Attribution-NonCommercial 9
Android
4.0 International 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 Commons Attribution-NonCommercial 10
Android
4.0 International License
Android Platform
Architecture

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 11
Android
4.0 International 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

12
13
System and user apps
● System apps have no special status
● The system apps function both as apps for users and to
provide key capabilities that developers can access from
their own app. For example, if your app would like to
deliver an SMS message, you don't need to build that
functionality yourself—you can instead invoke whichever
SMS app is already installed to deliver a message to the
recipient you specify.
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 14
Android
4.0 International 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
● Resource manager
● Notification manager
● Activity manager for life cycles and navigation
● Content providers to access data from other apps
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 15
Android
4.0 International License
Android runtime
For devices running Android version 5.0 (API level 21) or higher, each app
runs in its own process and with its own instance of the Android Runtime
(ART). ART is written to run multiple virtual machines on low-memory
devices by executing DEX files, a bytecode format designed specially for
Android that's optimized for minimal memory footprint. Build toolchains,
such as Jack, compile Java sources into DEX bytecode, which can run on
the Android platform.
Prior to Android version 5.0 (API level 21), Dalvik was the Android runtime

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 16
Android
4.0 International License
C/C++ libraries

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


system components and services.
For example, you can access OpenGL ES through the
Android framework’s Java OpenGL API to add support for
drawing and manipulating 2D and 3D graphics in your
app.
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 17
Android
4.0 International License
Hardware Abstraction Layer (HAL)
The hardware abstraction layer (HAL) provides standard interfaces that
expose device hardware capabilities to the higher-level Java API
framework. The HAL consists of multiple library modules, each of
which implements an interface for a specific type of hardware
component, such as the camera or bluetooth module. When a
framework API makes a call to access device hardware, the Android
system loads the library module for that hardware component.

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 18
Android
4.0 International License
Linux Kernel
1. The foundation of the Android platform is the Linux
kernel. For example, the Android Runtime (ART) relies on
the Linux kernel for underlying functionalities such as
threading and low-level memory management.
2. Using a Linux kernel allows Android to take advantage
of key security features and allows device manufacturers
to develop hardware drivers for a well-known kernel.
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 19
Android
4.0 International License
Android versions

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 20
Android
4.0 International License
Initial
Code Version Linux kernel API Initial
release Code Version Linux kernel API
name number version[3] level release
date name number version[3] level
date
(No September
1.0 ? 1
codename) 23, 2008 Ice Cream October 18,
4.0 – 4.0.4 3.0.1 14 – 15
Sandwich 2011
February 9,
Petit Four 1.1 2.6 2 3.0.31 to
2009 Jelly Bean 4.1 – 4.3.1 July 9, 2012 16 – 18
3.4.39
April 27,
Cupcake 1.5 2.6.27 3 October 31,
2009 KitKat 4.4 – 4.4.4 3.10 19 – 20
2013
September
Donut 1.6 2.6.29 4 November
15, 2009 Lollipop 5.0 – 5.1.1 3.16 21 – 22
12, 2014
October 26,
Eclair 2.0 – 2.1 2.6.29 5–7 October 5,
2009 Marshmallow 6.0 – 6.0.1 3.18 23
2015
May 20,
Froyo 2.2 – 2.2.3 2.6.32 8 Nougat 7.0 – 7.1.2 4.4
August 22,
24 – 25
2010 2016
December 6, August 21,
Gingerbread 2.3 – 2.3.7 2.6.35 9 – 10 Oreo 8.0 – 8.1 4.10 26 – 27
2010 2017
February 22, 4.4.107,
Honeycomb 3.0 – 3.2.6 2.6.36 11 – 13 August 6,
2011 Pie 9.0 4.9.84, and 28
2018
4.14.42

21
Android Q Or Android 10. Breaking the 10-year history of
naming Android releases after desserts, Google in 2019
announced the new version as just Android 10.
Google has released its latest big update in 2020 called
Android 11 “R”, which is rolling out now to the firm's Pixel
devices, and to smartphones from a handful of third-party
manufacturers.
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 22
Android
4.0 International License
App Development

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 23
Android
4.0 International 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 Commons Attribution-NonCommercial 24
Android
4.0 International 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 Commons Attribution-NonCommercial 25
Android
4.0 International 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 Commons Attribution-NonCommercial 26
Android
4.0 International License
Component types

● Activity is a single screen with a user interface


● Service performs long-running tasks in background
● Content provider manages shared set of data
● Broadcast receiver responds to system-wide
announcements(e.g “Low Battery” message from
system/app can be received and can act upon that)

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 27
Android
4.0 International License
Android Studio

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 28
Android
4.0 International License
What is Android Studio?
● Android IDE
● Project structure
● Templates
● Layout Editor
● Testing tools
● Gradle-based build
● Log Console
● Debugger
● Monitors
● Emulators
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 29
Android
4.0 International License
Installation Overview
● Mac, Windows, or Linux
● Requires Java Development Kit (JDK) 1.7 or better from
Oracle Java SE downloads page
● Set JAVA_HOME to JDK installation location
● Download and install Android Studio from
http://developer.android.com/sdk/index.html

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 30
Android
4.0 International License
Creating Your
First Android App

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 31
Android
4.0 International License
Start Android Studio

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 32
Android
4.0 International License
Create a project inside Android Studio

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 33
Android
4.0 International License
Name your app

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 34
Android
4.0 International 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.
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 35
Android
4.0 International License
Name your activity
● Good practice to
name main activity
MainActivity and
activity_main layout

● Use AppCompat

● Generating layout
file is convenient
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 36
Android
4.0 International License
Android Studio Panes
Layout
Editor

Project
Files

Android Monitors:
logcat: log messages

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 37
Android
4.0 International 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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 38
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 39
Android
4.0 International License
Run your app
1. Run

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

Tools > Android > AVD Manager or:

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 41
Android
4.0 International License
Configure virtual device
1. Choose hardware 2. Select Android Version
3. Finalize

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 42
Android
4.0 International License
Run on a virtual device

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 43
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 44
Android
4.0 International License
Get feedback as your app runs
● As the app runs, Android Monitor logcat shows information
● You can add logging statements to your app that will show
up in logcat.

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 45
Android
4.0 International License
Logging
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…”);
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 46
Android
4.0 International License
Android Monitor > logcat pane

1. Log statements in code.


2. logcat pane shows system
and logging messages

● Set filters to see what's important to you


● Search using tags
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 47
Android
4.0 International License
Layouts and resources for
the UI

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 48
Android
4.0 International License
Views

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 49
Android
4.0 International License
Everything you see is a view
If you look at your mobile device,
every user interface element that you
see is a View.

Views

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 50
Android
4.0 International 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)
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 51
Android
4.0 International License
Examples of view subclasses

Button CheckBox

EditText RadioButton

Slider Switch

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 52
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 53
Android
4.0 International License
Create views and layouts

● Android Studio layout editor: visual representation of XML


● XML editor
● Java code

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 54
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 55
Android
4.0 International 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"
/>
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 56
Android
4.0 International 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"

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 57
Android
4.0 International License
Create View in Java code
context
In an Activity:

TextView myText = new TextView(this);


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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 58
Android
4.0 International 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);

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 59
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 60
Android
4.0 International License
ViewGroup and
View hierarchy

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 61
Android
4.0 International License
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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 62
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 63
Android
4.0 International License
Common Layout Classes

LinearLayout ConstraintLayout GridLayout TableLayout

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 64
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 65
Android
4.0 International 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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 66
Android
4.0 International License
Hierarchy of viewgroups and views

ViewGroup Root view is always a ViewGroup

ViewGroup View View

View View View

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 67
Android
4.0 International License
View hierarchy and screen layout

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 68
Android
4.0 International License
View hierarchy in the layout editor

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 69
Android
4.0 International License
Layout created in XML
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
... />
<TextView
... />
<Button
... />
</LinearLayout
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 70
Android
4.0 International 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);

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 71
Android
4.0 International 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);

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 72
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 73
Android
4.0 International License
The layout
editor and
Constraint
Layout

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 74
Android
4.0 International License
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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 75
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 76
Android
4.0 International 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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 77
Android
4.0 International License
Autoconnect

● Enable Autoconnect in
toolbar if disabled
● Drag element to any part
of a layout
● Autoconnect generates
constraints against
parent layout
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 78
Android
4.0 International License
ConstraintLayout handles

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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 79
Android
4.0 International License
Align elements by baseline
1. Click the baseline
constraint button
2. Drag from baseline to
other element's baseline

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 80
Android
4.0 International License
Attributes pane

● Click the Attributes tab


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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 81
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 82
Android
4.0 International 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)

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 83
Android
4.0 International 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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 84
Android
4.0 International License
Set attributes example: TextView

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 85
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 86
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 87
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 88
Android
4.0 International License
Event Handling

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 89
Android
4.0 International License
Events

Something that happens


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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 90
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 91
Android
4.0 International 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();
}
}

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 92
Android
4.0 International 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();
}
});

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 93
Android
4.0 International License
Resources and
measurements

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 94
Android
4.0 International License
Resources

● Separate static data from code in your layouts.


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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 95
Android
4.0 International License
Where are the resources in your project?

resources and resource files


stored in res folder

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 96
Android
4.0 International 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"
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 97
Android
4.0 International 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)
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 98
Android
4.0 International License
Android Developer Fundamentals

Activities and
Intents

Lesson 2

This
Thiswork
workis islicensed
licensedunder
undera aCreative
Creative
Introduction to
Android Developer Fundamentals Activities Commons
CommonsAttribution-NonCommercial
Attribution-NonCommercial 99
Android
4.0
4.0International
InternationalLicense
License
Activities
(high-level view)

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 100
Android
4.0 International License
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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 101
Android
4.0 International 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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 102
Android
4.0 International License
Examples of activities

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 103
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 104
Android
4.0 International 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 105
Android
4.0 International License
Implementing
Activities

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 106
Android
4.0 International License
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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 107
Android
4.0 International 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>
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 108
Android
4.0 International License
2. Define Activity Java class

public class MainActivity extends AppCompatActivity {


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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 109
Android
4.0 International 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
}

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 110
Android
4.0 International License
4. Declare activity in Android manifest

<activity android:name=".MainActivity">

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 111
Android
4.0 International License
4. Declare main activity in manifest
Main Activity needs to include intent to start from launcher icon

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 112
Android
4.0 International License
Intents

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 113
Android
4.0 International License
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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 114
Android
4.0 International License
What can intents do?
● Start activities
○ A button click starts a new activity for text entry
○ Clicking Share opens an app that allows you to post a photo

● Start services
○ Initiate downloading a file in the background

● Deliver broadcasts
○ The system informs everybody that the phone is now charging
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 115
Android
4.0 International License
Explicit and implicit intents
Explicit Intent
● Starts a specific activity
○ Main activity starts the ViewShoppingCart activity

Implicit Intent
● Asks system to find an activity that can handle this request
○ Clicking Share opens a chooser with a list of apps

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 116
Android
4.0 International License
Starting
Activities

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 117
Android
4.0 International License
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);

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 118
Android
4.0 International 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);

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 119
Android
4.0 International 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);
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 120
Android
4.0 International License
How Activities Run
● All activities 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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 121
Android
4.0 International License
Sending and
Receiving Data

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 122
Android
4.0 International License
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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 123
Android
4.0 International 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
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 124
Android
4.0 International 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")));
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 125
Android
4.0 International 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.

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 126
Android
4.0 International License
Sending data to an activity with extras
public static final String MESSAGE_KEY =
“My Message";

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


String message = "Hello Activity!";
intent.putExtra(MESSAGE_KEY, message);
startActivity(intent);

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 127
Android
4.0 International 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.

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 128
Android
4.0 International 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

3. Implement onActivityResult() in first activity


This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 129
Android
4.0 International 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"

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 130
Android
4.0 International License
1. startActivityForResult() Example

public static final int CHOOSE_FOOD_REQUEST = 1;

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


startActivityForResult(intent, CHOOSE_FOOD_REQUEST);

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 131
Android
4.0 International 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();
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 132
Android
4.0 International License
3. Implement onActivityResult()
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_FOOD_REQUEST) { // Identify activity
if (resultCode == RESULT_OK) { // Activity succeeded
String reply = data.getStringExtra(SecondActivity.EXTRA_REPLY);
// … do something with the data
}}}

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 133
Android
4.0 International License
Navigation

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 134
Android
4.0 International License
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

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 135
Android
4.0 International 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?

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 136
Android
4.0 International 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 app's action bar
● controlled by defining parent-child relationships
between activities in the Android manifest
This work is licensed under a Creative
Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 137
Android
4.0 International License
Back navigation
● Back stack preserves history of recently viewed screens
● Back stack contains all the activities 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
● Launching an activity from the home screen starts a new task
● Navigate between tasks with the overview or recent tasks screen

This work is licensed under a Creative


Introduction to
Android Developer Fundamentals Commons Attribution-NonCommercial 138
Android
4.0 International License
Up navigation
● Goes to parent of current activity
● Define an activity's parent in Android manifest
● Set parentActivityName
<activity
android:name=".ShowDinnerActivity"
android:parentActivityName=".MainActivity" >
</activity>

This work is licensed under a Creative


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

You might also like