Post on 14-Aug-2020
Android IntroductionArchitecture
Activities, Lifecycle
Development Environment
1
Why Android?
2
Pervasive Mobile Platform
- Runs on hundreds of millions of mobile phones, tablets
- World’s most popular & frequently installed mobile OS
- Open Source (minimum-definition).
Developer Friendly
- Familiar language (e.g. Java, Kotlin)
- Multi-platform support
- Android Studio, IntelliJ support
See http://developer.android.com/tools/index.html
Development Environment
3
Java JDK
- https://adoptopenjdk.net/index.html
Android SDK
- https://developer.android.com/studio
- Included in the Android Studio installation
Development Environment
- Plan on using IntelliJ or Android Studio
- Examples are provided as IntelliJ projects
- https://www.jetbrains.com/idea/download
Architecture
5
Applications are built in Java (or Kotlin)- Android compiler generates an Android Package (.apk file), which
contains code, resources etc.- Package is installed using SDK, which sets up environment for that app.
Applications run securely in the environment- Android is a Linux environment where every app is a distinct user!- When the app is installed, permissions are set to restrict access
(resources, data).- Every app runs in its own process.- Apps must request access to shares resources (e.g. file system,
camera)
As a developer, you create a manifest file in your package that describes how your application should be installed, what permissions it requires.
6
Setup
7
1. Download and install Java JDK.
2. Download and install Android Studio to get the Android SDK: https://developer.android.com/studio/
3. IntelliJ embeds an Android plugin that will use the Android SDK. Go to Settings to configure it (next slide).
4. Open a sample project (or create one) to check that it works.
SDK Manager
8
Set the path to your Android SDK installation folder
Check the APIs you want
Setup
9
Android SDK tools are accessed through a drop-down menu in your IDE.
AVD Manager: manage Android Virtual Devices (AVDs) for testing.
SDK Manager: maintaining the SDK itself.
AVD Manager
10
Sample Code
11
File -> Open (Project from Examples Directory)
Run, Select Deployment Target- Can launch AVD or push to connected device
Getting Started: Project Wizard
12
Company Domain
- only important if you release your app, can just use something like:
cs349.uwaterloo.ca
API to target is the minimum Android version on target devices
- Use API 15 for Phone and Tablet (we won’t be doing anything restrictive)
SDK version is the version of the dev tools, libraries etc.
- Android Studio defaults to 29
Activity: Whatever you start with, do NOT use fragments
Project Structure
13
Manifest (app/manifests/)
- Application setting
Java (app/java/)
- (*.java) source code
Resources (app/res/)
- layout: (*.xml) UI layout and View definitions
- values: (*.xml) constants like strings, colours, …
- also bitmaps and SVG images (mipmap*, drawable*, ….)
Manifest - Activities
14
Metadata about the app
App components, Intent filters
<applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme"><activity android:name=".MainActivity">
<intent-filter><action android:name="android.intent.action.MAIN" /><category
android:name="android.intent.category.LAUNCHER" /></intent-filter>
</activity></application>
Manifest – Permissions
15
Android must request permission to access sensitive user data
User is prompted once on application launch (or on-demand with more recent versions of the OS)
Do not request more than you need (please!)
<manifest><uses-permission
android:name="android.permission.INTERNET" /><uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission
android:name="android.permission.SEND_SMS" /></manifest>
App Resources
16
Each type of resource in located a specific subdirectory of your project's res/ directory
Access them using resource IDs that are generated in the project's R class
app/ manifest/ java/ res/
drawable/ graphic.png
layout/ activity_main.xml
mipmap/ icon.png
values/ strings.xml
App Components
17
An application can consist of multiple “application components”.
Each component is an entry point through which the system or a user can enter or access your application.
Components Description
Activity Single-screen of an application
Service Long-running background process
Content provider Provides shared set of application data
Broadcast receiver Responds to system broadcast events
Activities
18
The “standard” application component is an Activity
Typically represents a single screen of your application (and you may have multiple activities, one of which will be running at a time).
- Not a view, since it can contains both model + view
One activity will be the Main entry point for your application (aka Main).
Activity Navigation
You can have multiple activities in your application (e.g. different screens), and switch between them as-needed.
- Activities can create other activities (i.e. “back stack” of activities that you can reach by using the back button)
- Navigation forward/back through activities is typically triggered by user actions
19
Activity Lifecycle
20
Activities have an explicit lifecycle, and have a state reflecting what they are doing (e.g. “started” or “stopped”)
Changing state fires a callback method that corresponds to that state (e.g. going from “stopped” to ”started” causes the onStart() method to fire).
RunningPaused
/ Stopped
https://developer.android.com/guide/components/activities/activity-lifecycle.html
Managing the Activity Lifecycle
21
Core callback functions:
onCreate()- being created or launching
onStart()- becomes visible to user
onResume()- prior to user interaction
onPause()- loses focus or background
onStop()- no longer visible to user
onDestroy()- being recycled and freed
Interrupted Workflow
22
Applications can stop at any time (i.e. user quits, OS kills it, user presses the Back button- the activity transitions through
the onPause(), onStop(), and onDestroy()callbacks.
- the activity is also removed from the stack.
onRestoreInstanceState() is automatically called by the system after onStart().
onSaveInstanceState() is automatically called by the system after onStop().
To preserve simple transient-state data, override these methods- Save data in onSaveInstanceState()- Restore data in onRestoreInstanceState()
Interrupted Workflow
23
Applications can stop at any time (i.e. user quits, OS kills it, user presses the Back button- the activity transitions through
the onPause(), onStop(), and onDestroy()callbacks.
- the activity is also removed from the stack.
onRestoreInstanceState() is automatically called by the system after onStart().
onSaveInstanceState() is automatically called by the system after onStop().
To preserve simple transient-state data, override these methods- Save data in onSaveInstanceState()- Restore data in onRestoreInstanceState()
Intents
24
An Intent is a messaging object you can use to request an action from another application component- Starting an activity- Starting a service- Delivering a broadcast
This allows an application to use other application services! e.g. Instagram app can request access to the Camera activity to take a picture.- Eliminates the need to have functionality embedded in an application.- Allows the OS to control access/permissions to services.
We use intents to pass data between activities.- Basically a data structure holding an abstract description of an action
https://developer.android.com/guide/components/intents-filters.html
Intents
25
Use startActivity() or startActivityForResult() methods to launch an activity with an intent.
- Use onActivityResult() to retreive the result of the activitylaunched with startActivityForResult()
- Can call explicit named activity (e.g. mySettingsActivity) or an implicit activity based on its capabilities (e.g. some camera activity)
Intents
26
- Explicit intent that starts a download background service.
- Implicit intent that sends fires an intent to send a text message.
Intents
27
- Start an activity to take a picture and retreive it
- Retrieve the taken photo from the camera activity that took the photo
Android UI DevelopmentView hierarchies
Using different layouts
Using UI widgets
MVC
29
Building User Interfaces
30
android.view.ViewGroup
Abstract container class that includes the layout
Subclasses:
LinearLayout, RelativeLayout, GridLayout, …
android.view.View
Base widget class (i.e. drawing and event handling)
Subclasses:
android.widget.Button
android.widget.ImageView
android.widget.ProgressBar
Android.widget.TextView
...
User Interface Classes
31
UI is built using a hierarchy of View and ViewGroup
- A ViewGroup is an invisible container that defines the layout structure for View and other ViewGroup objects
- A View usually draws something the user can see and interact with
https://developer.android.com/guide/topics/ui/declaring-layout.html
Common Layouts
32
Each subclass of the ViewGroup class provides a unique way to display the views you nest within it
Grid ViewDisplays items in a two-dimensional,
scrollable grid
Linear LayoutA layout that organizes
its children into a single horizontal or
vertical row
Relative LayoutEnables us to specify the location of child objects relative to
each other or to the parent.
Specialized Layouts
33
RecyclerView
Display very long lists of items (and have the OS load/unload the items as you scroll).
https://developer.android.com/guide/topics/ui/layout/recyclerview
CardView
Customized cards (e.g. panels) that needs to be repeated over and over again.
e.g. blog posts each with a card
https://developer.android.com/guide/topics/ui/layout/cardview
UI Definition and Layout
34
Layout can be handled in one of two ways:
- Programmatic: write code. You write code to instantiate ViewGroups, Views and bind them together (like in Java FX GuiBuilder).
- Declarative: use XML to describe your layout. In XML describe the screen elements (view groups and views) along with properties, and then tell your application to dynamically load it.
Using XML is the preferred way
- Android Studio & IntelliJ both include a GUI builder to make this easier!
Layout: WYSIWYG Version
36
Layout: XML Version
37
Layout Example
38
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent">
<EditTextandroid:id="@+id/editTextName”android:layout_alignParentTop="true”android:layout_marginTop="30dp"android:ems="12"android:text="@string/name”… />
<Buttonandroid:id="@+id/btnConfirm"android:layout_below="@id/editTextName"android:layout_marginTop="40dp"android:text="@string/confirm"… />
</RelativeLayout>
Layout
39
When you compile your app, each XML layout file is compiled into a View resource
calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name.
app/java/MainActivity.java
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);
}
Linear Layout
40
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.
You can specify the layout direction with the android:orientationattribute.
All children of a LinearLayout are stacked one after the other
- a vertical layout will only have one child per row, no matter how wide is it
- a horizontal layout will only be one row high
https://developer.android.com/guide/topics/ui/layout/linear.html
Key Attributes
41
Orientation
- Should the layout be a column or a row? Use "horizontal" for a row, "vertical" for a column.
Fill model
- MATCH_PARENT: the view wants to be as big as its parent
- WRAP_CONTENT: the view wants to be just large enough to fit its own internal content
Weight
- android:layout_weight attribute assigns an "importance" value to a view in terms of how much space it should occupy on the screen.
Attributes
42
Gravity
- Specifies how an object should position its content, on both the X and Y axes (top, bottom, center,…)
Padding/margin
- Setting padding/margin
LinearLayout
43
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingLeft="16dp"android:paddingRight="16dp"android:orientation="vertical" ><EditText
…/><EditText
…/>
<Button…
/></LinearLayout>
LinearLayout
44
<LinearLayout …><EditText
android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/to" />
<EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/subject" />
<EditTextandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:gravity="top"android:hint="@string/message" />
<Buttonandroid:layout_width="100dp"android:layout_height="wrap_content"android:layout_gravity="right"android:text="@string/send" />
</LinearLayout>
Fill
Relative Layout
45
RelativeLayout is a view group that displays child views in relative positions.
The position of each view can be specified as
- relative to sibling elements (such as to the left-of or below another view)
- in positions relative to the parent’s area (such as aligned to the bottom, left or center).
https://developer.android.com/guide/topics/ui/layout/relative
View Positioning
46
RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID).
By default, all child views are drawn at the top-left of the layout
Example of some layout properties :
- android:layout_alignParentTop
- android:layout_centerVertical
- android:layout_below
- android:layout_toRightOf
- More: RelativeLayout.LayoutParams
https://developer.android.com/guide/topics/ui/layout/relative
View Positioning in Relative Layout
47
android:layout_aboveandroid:layout_below
android:layout_toLeftOfandroid:layout_toRightOf
android:layout_alignBottomandroid:layout_alignTop
android:layout_alignLeftandroid:layout_alignRight
Widget 1
Widget 2
Widget 2
Widget 1
Widget 1Widget 2 Widget 2Widget 1
Widget 1Widget 2
Widget 1Widget 2
Widget 1
Widget 2
Widget 1
Widget 2
Relative layout alignment parameters
48
android:layout_alignParentTop
android:layout_alignParentLeft
android:layout_alignParentRight
android:layout_centerInParent
android:layout_centerVertical
android:layout_centerHorizontal
android:layout_alignParentBottom
49
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingLeft="16dp"android:paddingRight="16dp" ><EditText
…/><Spinner
…/><Spinner
…/><Button
…/>
</RelativeLayout>
Relative Layout
50
<RelativeLayout …<EditText
android:id="@+id/name"android:layout_width="match_parent"android:layout_height="wrap_content” />
<Spinnerandroid:id="@+id/times"android:layout_width="96dp"android:layout_height="wrap_content"android:layout_below="@id/name"android:layout_alignParentRight="true" />
<Spinnerandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_below="@id/name"android:layout_toLeftOf="@id/times”android:layout_alignParentLeft="true” />
<Buttonandroid:layout_width="96dp"android:layout_height="wrap_content"android:layout_below="@id/times"android:layout_alignParentRight="true"android:text="@string/done" />
</RelativeLayout>
Layout test
52
Check the layout with multiple screen sizes
Code Demo: WidgetDemo
53
Notes
- TextView
- EditText
- RadioButton
- CheckBox
- Spinners
- Relative Layout
- Linear Layout
- Nested Layout
Nested Layout
54
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextView
android:id="@+id/name_title"android:text=“@string/name">……
</TextView>……
<LinearLayoutandroid:layout_below="@+id/session">………<CheckBox
android:id="@+id/checkbox_morning"android:text="@string/morning”…… />
<CheckBox…… />
</LinearLayout></RelativeLayout>
Views
View
View (Widget)
55
Properties:
Background color, text, font, alignment, size, padding, margin, etc
Event Listeners and Handlers:
respond to various events such as: click, long-click, focus change, etc.
Set focus:
Set focus on a specific view requestFocus() or use XML tag <requestFocus />
Visibility:
You can hide or show views using setVisibility(…).
Views: TextViews
56
<TextViewandroid:id="@+id/txtHello"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!" />
TextView helloTextView = findViewById(R.id.txtHello);helloTextView.setText("CS349 W19");
Views: EditText
57
<EditTextandroid:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content”android:inputType="textPersonName" android:text=”@string/name” ><requestFocus/>
<EditText/>
EditText nameView = findViewById(R.id.name);String name = nameView.getText().toString();
Views: Buttons
58
<Buttonandroid:id="@+id/btnAlarm"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/alarm" />
https://developer.android.com/guide/topics/ui/controls/button.html
Button button = (Button) findViewById(R.id.btnAlarm);. . .
Responding to Events
59
<Buttonandroid:id="@+id/btnAlarm"……android:onClick="sendMessage"/>
/** Called in activity when the user touches the button */public void sendMessage(View view) {
// Do something in response to button click}
Button button = (Button) findViewById(R.id.btnAlarm);button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {// Do something in response to button click
}});
Option 1: Listeners
Option 2: Registered in Layout file
Radio Buttons
60
<RadioGroupandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><RadioButton
android:id="@+id/radio_yes"android:layout_width="wrap_content"android:layout_height="wrap_content"android:weight=”1"android:onClick="onRadioButtonClicked"android:text="@string/yes" />
<RadioButtonandroid:id="@+id/radio_no"android:layout_width="wrap_content"android:layout_height="wrap_content"android:weight=”1"android:onClick="onRadioButtonClicked"android:text="@string/no" />
</RadioGroup>
Radio Buttons
61
public void onRadioButtonClicked(View view) {// Is this button checked?boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clickedswitch (view.getId()) {
case R.id.radio_yes:if (checked)
// code for yesbreak;
case R.id.radio_maybe:if (checked)
// code for may bebreak;
case R.id.radio_no:if (checked)
// code for nobreak;
}}
https://developer.android.com/guide/topics/ui/controls/radiobutton
Checkboxes
62
<CheckBoxandroid:id="@+id/checkbox_morning"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="onCheckboxClicked"android:text="@string/morning" />
<CheckBoxandroid:id="@+id/checkbox_afternoon"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="onCheckboxClicked"android:text="@string/afternoon" />
https://developer.android.com/guide/topics/ui/controls/checkbox.html
Checkboxes
63https://developer.android.com/guide/topics/ui/controls/checkbox.html
public void onCheckboxClicked(View view) {// Is the view now checked?boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clickedswitch (view.getId()) {
case R.id.checkbox_morning:if (checked)// Add morning session
else// Remove morning sessionbreak;
case R.id.checkbox_afternoon:if (checked)// Add afternoon session
else// Remove afternoon sessionbreak;
}}
ImageView
64
Display images
Save image resources to drawable folder
- app/src/main/res/drawable/ <ImageView
android:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="wrap_content”android:src="@drawable/lollipop" />
Events
65
Android uses the Java event model with additional mobile events
- Event listener: interface for specific type of event
- Event handler: registered callback method to handle the event
Event Listener Event Handler Type of event
OnClickListener onClick() Touch, click
OnLongClickListener onLongClick() Press and hold
onTouchListener onTouch() Generic touch events; can beused for touch_up, second_touch
Multiple Views ApplicationUsing intents to launch activities
MVC in Android
ViewModel
68
Activity Lifecycle
69
Usually, one view per activity
Only one activity is running at any given time
We often want to let users navigate between different views.
How can we share data between views? Intents
RunningRunning
Paused
Start Another Activity: Pass Data
70
int version = 0;switch (radio_id){
case R.id.radioButton1:version = 6;break;
…
Intent intent = new Intent(this, VersionActivity.class);intent.putExtra("version", version); // data to passstartActivity(intent);
Start Another Activity: Receive Data
71
// Get the Intent that started this activity //and extract the value in intIntent intent = getIntent();int v = intent.getIntExtra("version",0);
// Set the string match to the valueTextView label = findViewById(R.id.version_txt);switch(v){
case 6:label.setText(R.string.v6);
Return “Home” to Previous Activity
72
In Manifest file, specify “parentActivity”
<applicationandroid:allowBackup="true”
…>
<activity android:name=".MainActivity">…
</activity>
<activity android:name=".VersionActivity"android:parentActivityName=".MainActivity”>
</activity></application>
MVC in Android
73
With MVC, there is a data model that ensures consistent state across views.
Android makes MVC difficult, because
Activities cannot easily share data (since they exist independently)
An activity that creates a model may be later paused or destroyed.
How do we share our data across activities? Options:
1. Save and restore data within each activity.
2. Create a static model that is shared between activities.
3. Use Google’s ViewModel, a persistent Model class that survives activity changes.
MVC Structure Option 1: Save and Restore Data in Views
74
view2.xmlView2
MainActivity
Model
view1.xmlView1
ViewGroup
ViewGroup
Activity Other ClassUI xml
Code Demo: MVC1
75
Views as Android ViewGroups
- similar to desktop MVC we discussed earlier
Notes:
- Model essentially identical to desktop Java
- “Inflating” view layouts into main view
- onPostCreate() when inflating view layouts
- Save and restore model
Recreating an Activity
76
protected void onSaveInstanceState(Bundle outState) {outState.putInt("Counter", model.getCounterValue());...
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {model.setCounterValue(savedInstanceState.getInt("Counter"));...
}
Use built-in methods to save and restore model state.
Application
MVC Structure Option 2: Shared Static Model
77
View1Activity
Model
view1.xmlcontentView
Activity Other ClassUI xml
View2Activity
view2.xmlcontentView
intents
Code Demo: MVC2
78
Views as Activities, global static model
Notes:
- Application class- onDestroy(), deleteObserver()- Create options menu
- Intents to start activity- finish()- no need to persist model!
MVC Structure Option 3: ViewModel
79
Google provides a ViewModel helper class
Use to asynchronously fetch data.
But NOT persistent across Activities.
https://developer.android.com/topic/libraries/architecture/viewmodel#java