Android Introduction Architecture Activities, Lifecycle - - PowerPoint PPT Presentation

android introduction
SMART_READER_LITE
LIVE PREVIEW

Android Introduction Architecture Activities, Lifecycle - - PowerPoint PPT Presentation

Android Introduction Architecture Activities, Lifecycle Development Environment 1 Why Android? Pervasive Mobile Platform - Runs on hundreds of millions of mobile phones, tablets - Worlds most popular & frequently installed mobile OS


slide-1
SLIDE 1

Android Introduction

Architecture Activities, Lifecycle Development Environment

1

slide-2
SLIDE 2

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
slide-3
SLIDE 3

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
slide-4
SLIDE 4

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.

slide-5
SLIDE 5

6

slide-6
SLIDE 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.

slide-7
SLIDE 7

SDK Manager

8

Set the path to your Android SDK installation folder Check the APIs you want

slide-8
SLIDE 8

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.
slide-9
SLIDE 9

AVD Manager

10

slide-10
SLIDE 10

Sample Code

11

  • File -> Open (Project from Examples Directory)
  • Run, Select Deployment Target
  • Can launch AVD or push to connected device
slide-11
SLIDE 11

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

slide-12
SLIDE 12

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*, ….)

slide-13
SLIDE 13

Manifest - Activities

14

  • Metadata about the app
  • App components, Intent filters

<application android: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>

slide-14
SLIDE 14

Manifest – Permissions

15

  • Android must request permission to access

sensitive user data

  • User is prompted once on application launch (or
  • n-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>

slide-15
SLIDE 15

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

slide-16
SLIDE 16

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

slide-17
SLIDE 17

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).

slide-18
SLIDE 18

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

slide-19
SLIDE 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).

Running Paused / Stopped

https://developer.android.com/guide/components/activities/activity-lifecycle.html

slide-20
SLIDE 20

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
slide-21
SLIDE 21

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,
  • verride these methods
  • Save data in onSaveInstanceState()
  • Restore data in onRestoreInstanceState()
slide-22
SLIDE 22

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,
  • verride these methods
  • Save data in onSaveInstanceState()
  • Restore data in onRestoreInstanceState()
slide-23
SLIDE 23

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

slide-24
SLIDE 24

Intents

25

  • Use startActivity() or startActivityForResult() methods to launch

an activity with an intent.

  • Use onActivityResult() to retreive the result of the activity

launched with startActivityForResult()

  • Can call explicit named activity (e.g. mySettingsActivity) or an

implicit activity based on its capabilities (e.g. some camera activity)

slide-25
SLIDE 25

Intents

26

  • Explicit intent that starts a download background service.
  • Implicit intent that sends fires an intent to send a text message.
slide-26
SLIDE 26

Intents

27

  • Start an activity to take a picture and retreive it
  • Retrieve the taken photo from the camera activity that took the

photo

slide-27
SLIDE 27

Android UI Development

View hierarchies Using different layouts Using UI widgets MVC

29

slide-28
SLIDE 28

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 ...

slide-29
SLIDE 29

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

slide-30
SLIDE 30

Common Layouts

32

  • Each subclass of the ViewGroup class provides a unique way to

display the views you nest within it Grid View Displays items in a two-dimensional, scrollable grid Linear Layout A layout that organizes its children into a single horizontal or vertical row Relative Layout Enables us to specify the location of child

  • bjects relative to

each other or to the parent.

slide-31
SLIDE 31

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/lay
  • ut/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/layo ut/cardview

slide-32
SLIDE 32

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 Gui Builder).

  • 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!

slide-33
SLIDE 33

Layout: WYSIWYG Version

36

slide-34
SLIDE 34

Layout: XML Version

37

slide-35
SLIDE 35

Layout Example

38

<RelativeLayout xmlns: android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/editTextName” android:layout_alignParentTop="true” android:layout_marginTop="30dp" android:ems="12" android:text="@string/name” … /> <Button android:id="@+id/btnConfirm" android:layout_below="@id/editTextName" android:layout_marginTop="40dp" android:text="@string/confirm" … /> </RelativeLayout>

slide-36
SLIDE 36

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); }

slide-37
SLIDE 37

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:orientation

attribute.

  • 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

slide-38
SLIDE 38

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

  • ccupy on the screen.
slide-39
SLIDE 39

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
slide-40
SLIDE 40

LinearLayout

43

<LinearLayout xmlns: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>

slide-41
SLIDE 41

LinearLayout

44

<LinearLayout …> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/to" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/subject" /> <EditText android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="top" android:hint="@string/message" /> <Button android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/send" /> </LinearLayout>

Fill

slide-42
SLIDE 42

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

slide-43
SLIDE 43

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

slide-44
SLIDE 44

View Positioning in Relative Layout

47

android:layout_above android:layout_below android:layout_toLeftOf android:layout_toRightOf android:layout_alignBottom android:layout_alignTop android:layout_alignLeft android:layout_alignRight

Widget 1 Widget 2 Widget 2 Widget 1 Widget 1 Widget 2 Widget 2 Widget 1 Widget 1 Widget 2 Widget 1 Widget 2 Widget 1 Widget 2 Widget 1 Widget 2

slide-45
SLIDE 45

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

slide-46
SLIDE 46

49

<RelativeLayout xmlns: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

slide-47
SLIDE 47

50

<RelativeLayout … <EditText android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content” /> <Spinner android:id="@+id/times" android:layout_width="96dp" android:layout_height="wrap_content" android:layout_below="@id/name" android:layout_alignParentRight="true" /> <Spinner android:layout_width="0dp" android:layout_height="wrap_content" android:layout_below="@id/name" android:layout_toLeftOf="@id/times” android:layout_alignParentLeft="true” /> <Button android:layout_width="96dp" android:layout_height="wrap_content" android:layout_below="@id/times" android:layout_alignParentRight="true" android:text="@string/done" /> </RelativeLayout>

slide-48
SLIDE 48

Layout test

52

  • Check the layout with multiple screen sizes
slide-49
SLIDE 49

Code Demo: WidgetDemo

53

  • Notes
  • TextView
  • EditText
  • RadioButton
  • CheckBox
  • Spinners
  • Relative Layout
  • Linear Layout
  • Nested Layout
slide-50
SLIDE 50

Nested Layout

54

<RelativeLayout xmlns: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> …… <LinearLayout android:layout_below="@+id/session"> ……… <CheckBox android:id="@+id/checkbox_morning" android:text="@string/morning” …… /> <CheckBox …… /> </LinearLayout> </RelativeLayout>

Views View

slide-51
SLIDE 51

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(…).
slide-52
SLIDE 52

Views: TextViews

56

<TextView android: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");

slide-53
SLIDE 53

Views: EditText

57

<EditText android: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();

slide-54
SLIDE 54

Views: Buttons

58

<Button android: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); . . .

slide-55
SLIDE 55

Responding to Events

59

<Button android: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
slide-56
SLIDE 56

Radio Buttons

60

<RadioGroup android: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" /> <RadioButton android: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>

slide-57
SLIDE 57

Radio Buttons

61

public void onRadioButtonClicked(View view) { // Is this button checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked switch (view.getId()) { case R.id.radio_yes: if (checked) // code for yes break; case R.id.radio_maybe: if (checked) // code for may be break; case R.id.radio_no: if (checked) // code for no break; } } https://developer.android.com/guide/topics/ui/controls/radiobutton

slide-58
SLIDE 58

Checkboxes

62

<CheckBox android:id="@+id/checkbox_morning" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onCheckboxClicked" android:text="@string/morning" /> <CheckBox android: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

slide-59
SLIDE 59

Checkboxes

63

https://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 clicked switch (view.getId()) { case R.id.checkbox_morning: if (checked) // Add morning session else // Remove morning session break; case R.id.checkbox_afternoon: if (checked) // Add afternoon session else // Remove afternoon session break; } }

slide-60
SLIDE 60

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" />

slide-61
SLIDE 61

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

  • nClick()

Touch, click OnLongClickListener

  • nLongClick()

Press and hold

  • nTouchListener
  • nTouch()

Generic touch events; can be used for touch_up, second_touch

slide-62
SLIDE 62

Multiple Views Application

Using intents to launch activities MVC in Android ViewModel

68

slide-63
SLIDE 63

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

Running Running Paused

slide-64
SLIDE 64

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 pass startActivity(intent);

slide-65
SLIDE 65

Start Another Activity: Receive Data

71

// Get the Intent that started this activity //and extract the value in int Intent intent = getIntent(); int v = intent.getIntExtra("version",0); // Set the string match to the value TextView label = findViewById(R.id.version_txt); switch(v){ case 6: label.setText(R.string.v6);

slide-66
SLIDE 66

Return “Home” to Previous Activity

72

  • In Manifest file, specify “parentActivity”

<application android:allowBackup="true” … > <activity android:name=".MainActivity"> … </activity> <activity android:name=".VersionActivity" android:parentActivityName=".MainActivity”> </activity> </application>

slide-67
SLIDE 67

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.

slide-68
SLIDE 68

MVC Structure Option 1: Save and Restore Data in Views

74

view2.xml View2 MainActivity Model view1.xml View1 ViewGroup ViewGroup

Activity Other Class UI xml

slide-69
SLIDE 69

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
slide-70
SLIDE 70

Recreating an Activity

76

protected void onSaveInstanceState(Bundle outState) {

  • utState.putInt("Counter", model.getCounterValue());

... } protected void onRestoreInstanceState(Bundle savedInstanceState) { model.setCounterValue(savedInstanceState.getInt("Counter")); ... } Use built-in methods to save and restore model state.

slide-71
SLIDE 71

Application

MVC Structure Option 2: Shared Static Model

77

View1Activity Model view1.xml contentView

Activity Other Class UI xml

View2Activity view2.xml contentView

intents

slide-72
SLIDE 72

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!
slide-73
SLIDE 73

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