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

Lecture 03

This document provides an overview of the GeoQuiz app, which is used as an example to demonstrate Android UI design and programming. The GeoQuiz app presents trivia questions to test the user's geography knowledge. It contains two main files - an XML layout file that defines the app's screen widgets, and a Java activity class file that controls app behavior and responds to user input. The document outlines how the app displays questions and accepts true/false responses from buttons. It also explains how to code the app to respond when the buttons are clicked, such as displaying a toast notification. Key Android concepts discussed include using XML IDs to reference views in Java code, setting onClick listeners, and important Android packages.

Uploaded by

Sovannak On
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Lecture 03

This document provides an overview of the GeoQuiz app, which is used as an example to demonstrate Android UI design and programming. The GeoQuiz app presents trivia questions to test the user's geography knowledge. It contains two main files - an XML layout file that defines the app's screen widgets, and a Java activity class file that controls app behavior and responds to user input. The document outlines how the app displays questions and accepts true/false responses from buttons. It also explains how to code the app to respond when the buttons are clicked, such as displaying a toast notification. Key Android concepts discussed include using XML IDs to reference views in Java code, setting onClick listeners, and important Android packages.

Uploaded by

Sovannak On
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

CS 

528 Mobile and Ubiquitous 
Computing
Lecture 3: Android UI, WebView, 
Android Activity Lifecycle
Emmanuel Agu
Android UI Design Example
GeoQuiz App
Reference: Android Nerd Ranch, pgs 1‐32
 App presents questions to test user’s 
knowledge of geography

 User answers by pressing True or False 
buttons

Question
 How to get this book?

User responds
by clicking True
or False
GeoQuiz App

 2 main files:
 activity_quiz.xml: to format app screen
 QuizActivity.java: To present question, accept True/False 
response
 AndroidManifest.xml also auto‐generated
GeoQuiz: Plan Out App Widgets
 5 Widgets  arranged hierarchically
GeoQuiz: activity_quiz.xml File listing
GeoQuiz: strings.xml File listing

• Define app strings


• True
• False
• Question
QuizActivity.java
 Initial QuizActivity.java code

onCreate Method is called


once Activity is created

specify layout XML file (activity_quiz.xml)

 Would like java code to respond to 
True/False buttons being clicked
Responding to True/False Buttons in Java

Write code in Java file to specify app’s


response when True/False buttons are clicked
2 Ways to Respond to Button Clicks
1. In XML: set android:onClick attribute

2. In java create a ClickListener object, override onClick 
method
 typically done with anonymous inner class
Recall: Approach 1: Button that responds to Clicks
Reference: Head First Android

1. In XML file (e.g. main.xml), set


android:onClick attribute to specify
(onLoveButtonClicked) to be invoked

2. In Java file (e.g. AndroidLove.java)


declare and implement
method/handler to take desired action
Background: User Interface Elements
 Views (buttons, widgets, etc) declared in XML are actually Java 
classes within Android
 Using XML declarations, Android actually creates corresponding 
Java objects (called inflating a view)

 View
 basic building block for Android UI
 Android class that represents a rectangular area on the screen
 Responsible for drawing and event handling

 View is the super class for:
 Textview, Imageview
 Controls such as buttons, spinners, seek bars, etc.
 ViewGroups which in turn is the super class for layouts 
ViewGroups ‐ Layouts
 Layouts: 
 invisible containers that store other Views
 Subclasses of ViewGroup
 Still a view but doesn't actually draw anything
 A container for other views
 Specifies options on how sub views (and view 
groups) are arranged
Approach 2: Create a ClickListener object, 
override onClick 
 First, get reference to Button in 
our Java file. How?

Need reference
to Buttons
R.Java Constants
 During compilation, XML resources (drawables, layouts, 
strings, views with IDs, etc) are assigned constants
 Sample R.Java file
Referring to Resources in Java File
 Can refer to resources in Java file using these constants
 Example 
Constant assigned to
R.layout.main at runtime

 In java file, R.java the constant corresponding to main.xml is 
argument of setContentView
Pass in layout file as
constant assigned to
R.layout.main
Referencing Widgets by ID
 Many widgets and containers appear only in XML. E.g. TextView
 No need to be referenced in Java code
 To reference a widget in Java code, you need its android:id
In java file, to reference/manipulate
In XML file, give the widget/view an ID view/widget use its ID to find it
i.e. assign android:id (call findviewbyID( ) )
Getting View References

 findViewById is implemented 
in base Activity class so it can 
be called in our java file (e.g. 
MainActivity.java)
 Argument of findViewById is 
constant of resource
 A generic view is returned  
(not subclasses e.g. buttons, 
TextView), so needs to cast
QuizActivity.java: Getting References to 
Buttons
 To get reference to buttons in java code

Declaration
in XML
QuizActivity.java: Setting Listeners
 Set listeners for True and False button

1.Set Listener Object 3. Overide onClick method 2. Create listener


For mTrueButton (insert your code to do object as anonymous
whatever you want as (unnamed) inner object
mouse response here)
QuizActivity.java: Adding a Toast
 A toast is a short pop‐up message 
 Does not require any input or action
 After user clicks True or False button, 
our app will pop‐up a toast to inform 
the user if they were right or wrong
 First, we need to add toast strings 
(Correct, Incorrect) to strings.xml

A toast
QuizActivity.java: Adding a Toast
 To create a toast, call the method:

Instance of Activity Resouce ID of the Constant to specifiy


(Activity is a subclass string that toast how long toast
of context) should display should be visible

 After creating toast, call toast.show( ) 
to display it
 For example to add a toast to our 
onClick( ) method:
QuizActivity.java: Adding a Toast
 Code for adding a toast

1.Set Listener Object 3. Overide onClick method 2. Create listener


For mTrueButton Make a toast object as anonymous
innner object
package com.bignerdranch.android.geoquiz;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class QuizActivity extends Activity {


QuizActivity.java: 
Button mTrueButton;
Complete Listing
Button mFalseButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);

mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.incorrect_toast, Toast.LENGTH_SHORT)
.show();
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.correct_toast, Toast.LENGTH_SHORT)
.show();
} QuizActivity.java: 
});
} Complete Listing
@Override
public boolean onCreateOptionsMenu(Menu menu) {
(Contd)
// Inflate the menu;
// this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}

}
Used if app has an
Action bar menu
Android UI in Java
Checkbox
 Has 2 states: checked and unchecked
 Clicking on checkbox toggles between these 2 states
 Used to indicate a choice (e.g. Add rush delivery)
 Since Checkbox widget inherits from TextView, its properties 
(e.g. android:textColor) can be used to format checkbox
 XML code to create Checkbox:
Making Checkbox Responsive

 2 ways to make Checkbox responsive: 
1. Set android:onClick attribute or 
2. Create a ClickListener object, override onClick method

 In Java code, the following commands may be used
 isChecked( ): to determine if checkbox has been checked
 setChecked( ): to force checkbox into checked or unchecked state
 toggle( ): to toggle current checkbox setting
Checkbox Example Java Code

Checkbox inherits from


CompoundButton

Register listener
OnCheckedChangeListener
to be notified when checkbox
state changes

Callback, called
When checkbox
state changes
Checkbox Example Result
Important Android Packages
 Android programs usually import packages at top. E.g.

 Important packages
 android*  Android application
 dalvik* Dalvik virtual machine support classes
 java.* Core classes and generic utilities 
(networking, security, math, etc)
 org.apache.http: HTTP protocol support
Ref: Introduction to Android
Programming, Annuzzi, Darcey & Conder
Toggle Button
 ToggleButton and Switches
 Like CheckBox has 2 states
 However, visually shows states on and off text

 XML code to create ToggleButton

 Can also set up an onCheckedChangeListener to be notified 
when user changes ToggleButton state
Switch Widget
 Android Switch widget shows state via small ON/OFF slider
 Added in API level 14
Switch Widget
 XML code for creating Switch

 Checkbox, ToggleButton and Switch inherit from 


CompoundButton
 Common API for
 toggle( )
 isChecked( )
 setChecked( )
Creating Checkbox, ToggleButton or Switch 
in Android Studio 
 Checkbox, Togglebutton and Switch widgets are in Android 
Studio palette
 Can drag and drop them unto app screen then configure  
properties
RadioButton and RadioGroup
 User can select only 1 option from a set
 set onClick method for each button
 Inherits from CompoundButton which 
inherits from TextView
 Format using TextView properties (font, 
style, color, etc)
 Can use methods isChecked( ), toggle( )
 Collected in RadioGroup
 sub class of LinearLayout
 Can have vertical or horizontal orientation
RadioButton and RadioGroup
 XML code to create Radio Button

 Available in Android Studio palette
SeekBar
 a slider
 Subclass of progress bar
 implement a SeekBar.OnSeekBarChangeListener to respond 
to user’s changes in setting
WebView Widget
WebView Widget
 A View that displays web pages
 Can be used for creating your own web browser
 OR just display some online content inside your app
 Uses WebKit rendering engine (lots of memory)
 http://www.webkit.org/
 Webkit used in many web browsers including Safari

 Web pages in WebView same look same as in Safari  
40
WebView

 Android 4.4, API level 19 added Chromium as 
alternative to WebKit

 Chromium: http://www.chromium.org/Home

 "Chromium WebView provides broad support 
for HTML5, CSS3, and JavaScript. 
 Supports most HTML5 features available in 
Chrome. 
 Also has faster JavaScript Engine (V8)

41
https://developer.android.com/about/versions/kitkat.html
WebView Widget Functionality

 Display Web page containing 
HTML, CSS, Javascript
 Navigation history of URLs to 
support forward and backwards 
 zoom in and out
 perform searches
 Additional functionality:
 Embed images in page
 Search page for string
 Deal with cookies 42
WebView Example
 Simple app to view and navigate web pages 
 XML code (e.g in res/layout/main.xml)

43
WebView Activity
 In onCreate, use loadURL to load website
 If website contains Javascript, enable Javascript

44
loadUrl( )

 loadUrl( ) Works with
 http:// and https:// URLs
 file//  URLs pointing to local filesystem
 file:/// android_asset/ URLs pointing to app’s assets (later)
 content:// URLs pointing to content provider that is 
streaming published content
WebView Example
 Add permission to AndroidManifest.xml for app to use 
Internet
 Also change style so no title bar

46
Android App Components
Android App Components
 Typical Java program starts from main( ) 

 Android app: No need to write a main
 Just define app components by creating sub‐classes of base 
classes already defined in Android
 4 main types of Android app components:
 Activities (already seen this)
 Services
 Content providers
 Broadcast receivers
Recall: Activities

 Activity: main building block of Android UI
 Analogous to a window or dialog box in a 
desktop application
 Apps 
 have at least 1 activity that deals with UI
 Entry point of app similar to main( ) in C
 typically have multiple activities
 Example: A camera app
 Activity 1:  to focus, take photo,  start activity 2
 Activity 2: to present photo for viewing, save it
Recall: Activities

 Each activity controls 1 or more screens
 Activities independent of each other 
 Can be coupled by control or data
 App Activities are sub‐class of Activity class
 Example:
Fragments
 Fragments enables 1 app to look different on phone vs tablet
 An activity can contain multiple fragments that are organized 
differently for phone vs tablet
 Fragments are UI components that can be attached to different 
Activities. 
 More later
Services
 Activities are short‐lived, can be shut down anytime (e.g 
when user presses back button)
 Services keep running in background
 Minimal need to interact with (independent of) any activity
 Typically an activity will control a service ‐‐ start it, pause it,  
get data from it
 Similar to Linux/Unix CRON job
 Example uses of services:
 Periodically check device’s GPS location by contacting Android location 
manager, and pass data to activity
 Check for updates to RSS feed 
 App Services are sub‐class of Services class
Android Platform Services
 Android Services can either be on:
 Android Platform (local)
 Google (remote)

 Android platform services:
 LocationManager: location‐based services.
 ViewManager and WindowManager: Manage display and User Interface
 AccessibilityManager: accessibility, support for physically impaired users
 ClipboardManager: access to device’s clipboard, for cutting and pasting 
content.
 DownloadManager: manages HTTP downloads in the background
 FragmentManager: manages the fragments of an activity.
 AudioManager: provides access to audio and ringer controls.
Google Services (In Google Cloud)
 Maps
 Location‐based services
 Game Services
 Authorization APIs
 Google Plus
 Play Services
 In‐app Billing
 Google Cloud Messaging
 Google Analytics
 Google AdMob ads
Content Providers
 Android apps can share data (e.g. contacts)
 Content Provider:
 Abstracts shareable data, makes it accessible through methods
 Applications can access that shared data by calling methods for the 
relevant content provider
 Example: We can write an app that:
 Retrieve’s contacts list from contacts content provider
 Adds contacts to social networking (e.g. Facebook)

Shared data
Content Providers
 Apps can also ADD to data through content provider. 
E.g. Add contact
 E.g. Our app can also share its data 
 App Content Providers are sub‐class of 
ContentProvider class
Broadcast Receivers
 The system, or applications, periodically broadcasts events
 Example broadcasts:
 Battery getting low
 Screen turns off
 Download completed
 New email arrived
 A broadcast receiver can listen for broadcasts, respond
 Our app can also initiate broadcasts
 Broadcast receivers 
 Typically don't interact with the UI 
 Commonly create a status bar notification to alert the user when 
broadcast event occurs
 App Broadcast Receivers are sub‐class of BroadcastReceiver
class
Quiz
 Pedometer App
 Component A: continously counts user’s steps even when user closes app, 
does other things on phone (e.g. youtube, calls)
 Component B: Displays user’s step count
 Component C: texts user’s friends every day with their step totals

 What should component A be declared as (Activity, service, 
content provider, broadcast receiver)
 What of component B?
 Component C?
Android’s Process Model
Android’s Process Model

 When user launches an app, Android forks a copy of 
a process called zygote that receives
 A copy of of the Virtual Machine (Dalvik)
 A copy of Android framework classes (e.g. Activity and 
Button)
 A copy of user’s app classes loaded from their APK file
 Any objects created by app or framework classes
Recall: Home, Back and Recents Button
Android Activity Stack
(Back vs Home Button)
Most recently
 Android maintains activity stack created is at Top

 While an app is running,  User currently

 Pressing Back button destroys the 
Activity 1 interacting with
me
app’s activity and returns app to 
whatever user was doing  Pressing Back or
previously (e.g. HOME screen)
Activity 2 destroying A1 will
bring me to the top

 If Home button is pressed, activity  Activity 3


is kept around for some time, NOT 
destroyed immediately
If Activities above
Activity N me use too many
resources, I’ll be
destroyed!
Android Activity LifeCycle
Starting Activities
 Android applications don't start with a call to main(String[])
 Instead callbacks invoked corresponding to app state. 
 Examples: 
 When activity is created, its onCreate( ) method invoked
 When activity is paused, its onPause( ) method invoked
 callback methods also invoked to destroy Activity /app
Activity Callbacks
 onCreate()
 onStart()
 onResume()
 onPause()
 onStop()
 onRestart()
 onDestroy()
Understanding the Lifecycle
 Many things could happen while app is running 
 Incoming call or text message, user switches to another app, etc

 Well designed app should NOT:
 Crash if interrupted or user switches to other app 
 Consume valuable system resources when user is not actively using it.
 Lose the user's state/progress (e.g state of chess game app) if they leave 
your app and return to it at a later time.
 Crash or lose the user's progress when the screen rotates between 
landscape and portrait orientation.
 E.g. Youtube video should continue at correct point after rotation
 To ensure the above, appropriate callback methods must be 
invoked appropriately

http://developer.android.com/training/basics/activity-lifecycle/starting.html
OnCreate( )
 Initializes activity once created
 The following operations are typically performed in 
onCreate() method:
 Inflate widgets and put them on the screen 
 (e.g. using layout files with setContentView( ) )
 Getting references to inflated widgets ( using findViewbyId( ) )
 Setting widget listeners to handle user interaction

 Note: Android OS calls apps’ onCreate( ) method, NOT the 
app
Activity State Diagram: Running App
 A running app is one that the user is 
currently using or interacting with 
 App is visible and in foreground
Activity State Diagram: Paused App
 An app is paused if it is visible but no 
longer in foreground
 E.g. blocked by a pop‐up dialog box
 App’s onPause( ) method is called to 
transition  from running to paused state

Paused

Running
Activity State Diagram: onPause( ) Method 
 Typical actions taken in onPause( ) method 
 Stop animations and CPU intensive tasks
 Stop listening for GPS, broadcast information
 Release handles to sensors (e.g GPS, camera) 
 Stop audio and video if appropriate

Paused

Running
Activity State Diagram: Resuming Paused App
 A paused app resumes running if it becomes 
fully visible and in foreground
 E.g. pop‐up dialog box blocking it goes away
 App’s onResume( ) method is called to 
transition  from paused to running state

Paused

Running
Activity State Diagram: Stopped App
 An app is stopped if it no longer visible and 
no longer in foreground
 E.g. user starts using another app 
 App’s onStop( ) method is called to transition  
from paused to stopped state

Running
onStop() Method
 An activity is stopped when the user:
 Receives phone call

 Starts a new application

 Activity 1 launches new Activity 2

 Activity instance and variables of stopped 
app are retained but no code is being 
executed by the activity
 If activity is stopped, in onStop( ) method, 
well behaved apps should
 save progress to enable seamless restart later
 Release all resources and save information 
(persistence)
Saving State
 If activities are paused or stopped, their states  (instance vars) 
are retained
 Even if activity is not in foreground
 When activity is destroyed the Activity object is destroyed
 can save information via onSaveInstanceState(Bundle outState) 
method. 
 Write data to Bundle (a data structure)
 Bundle given back when restarted
Activity State Diagram: Stopped App
 A stopped app can go back into running 
state if becomes visible and in foreground
 App’s onRestart( )  and onResume( ) 
methods called to transition from stopped
to running state

Running
Activity State Diagram: Starting New App
 To start new app, app is launched
 App’s onCreate( ), onStart( ) and 
onResume( ) methods are called 
 Afterwards new app is running
Simplified Lifecycle Diagram
ready to interact
with user
Activity Lifecycle
(Another Diagram)

http://developer.android.com/reference/android/app/Activity.htm
l
Quiz
 Whenever I watch YouTube video 
on my phone, if I stop at 2:31, next 
time I use the app, it restarts at 
2:31. 
 How do you think this is 
implemented?
 In which Activity life cycle method 
should code be put into?
 How?
Logging Errors in Android
Logging Errors in Android
 Android can log and display various levels of errors
 Error logging is in Log class of android.util package
 Turn on logging of different message types by calling 
appropriate method

Ref: Introduction to Android


Programming, Annuzzi, Darcey &
Conder

 Before calling any logging 
import  android.util.Log;
QuizActivity.java
 A good way to understand  Android 
lifecycle methods is to print debug 
messages when they are called
 E.g. print debug message from 
onCreate method below
QuizActivity.java
 Debug (d) messages have the form

 TAG indicates source of message
 Declare string for TAG

 Can then print a message in onCreate( )
QuizActivity.java
 Putting it all together
QuizActivity.java

 Can overide more 
lifecycle methods 
 Print debug 
messages from 
each method
 Superclass calls 
called in each 
method

 @Override asks 
compiler to ensure 
method exists in 
super class
QuizActivity.java Debug Messages

 Launching GeoQuiz app creates, starts and 
resumes an activity

 Pressing Back button destroys the activity 
(calls onPause, onStop and onDestroy)
QuizActivity.java Debug Messages
 Pressing Home button stops the activity

 Rotating device (e.g. portrait to 
landscape) kills current activity and 
creates new activity in landscape mode
Rotating Device & Device Configuration
 Rotation changes device configuration
 Device configuration: screen 
orientation/density/size, keyboard type, 
dock mode, language, etc.
 Apps can specify different resources to use 
for different device configurations
 E.g. use different app layouts for portrait vs 
landscape screen orientation
Rotating Device & Device Configuration
 How to  use different app layouts for portrait 
vs landscape screen orientation?
 When device in landscape, uses resources in 
res/layout‐land/
 Copy XML layout file (activity_quiz.xml) from 
res/layout to res/layout‐land/ and tailor it
 When configuration changes, current activity 
destroyed, onCreate (setContentView 
(R.layout.activity_quiz) called again
Dead or Destroyed Activity

 Dead, activity terminated (or never 
started)
 onDestroy( ) called to destroy a 
stopped app
 Two other states, Created and Started, 
but they are transitory onCreate ‐> 
onStart ‐> onResume
Activity Destruction
 App may be destroyed 
 On its own by calling finish 

 If user presses back button to navigate away from app

 Normal lifecycle methods handle this 
onPause() ‐> onStop() ‐> onDestroy
 If the system must destroy the activity (to recover resources or on an 
orientation change) must be able to recreate Activity
 If Activity destroyed with potential to be recreate later, system calls 
onSaveInstanceState (Bundle outState) method
onSaveInstanceState
onRestoreInstanceState()
 Systems write info about views to Bundle
 other (app‐specific) information must be 
saved by programmer
 E.g. board state in a board game such 
as mastermind
 When Activity recreated Bundle sent to 
onCreate and onRestoreInstanceState()
 use either method to restore state data / 
instance variables
Saving State on Activity Destruction
Saving Data Across Device Rotation
 Since rotation causes activity to be destroyed 
and new one created, values of variables lost 
or reset
 To stop lost or reset values, save them using 
onSaveInstanceState before activity is 
destroyed
 System calls onSaveInstanceState before 
onPause( ), onStop( ) and onDestroy( )
Saving Data Across Device Rotation
 For example, if we want to save the value of 
a variable mCurrentIndex during rotation
 First, create a constant as a key for storing 
data in the bundle 

 Then override onSaveInstanceState method
References
 Busy Coder’s guide to Android version 4.4
 CS 65/165 slides, Dartmouth College, Spring 2014
 CS 371M slides, U of Texas Austin, Spring 2014

You might also like