Lesson 4-Mobile Application Dev - Native App Dev With Android - vVLE
Lesson 4-Mobile Application Dev - Native App Dev With Android - vVLE
By the end of this section, you will have a solid foundation in native
application development with Java and be able to create your own
applications for Android. Whether you are an experienced programmer
or new to mobile development, this section will provide you with the
skills and knowledge you need to succeed in the exciting world of native
application development.
2
© 2022 e-Learning Centre, UCSC
Intended Learning Outcomes
3
© 2022 e-Learning Centre, UCSC
List of sub topics
4.1. Getting started with Android development
4.1.1. Introduction to Android development
4.1.2. Setting up the tools and environment
4.2. Working with User Interfaces
4.2.1. App manifest and resources
4.2.2. Activities and Fragments (Activity Life Cycle, Fragment Life Cycle)
4.2.3. Layouts, Adapters, Action bar, Dialogs and Notifications
4.3. Data and App interaction
4.3.1. Intents and Broadcast
4.3.2. Preferences and Saving
4.3.3. Content Providers and Services
4.3.4. AsyncTask and AsyncTaskLoader
4.4. Sensors and Communication
4.4.1. Sensors (Sensor Identification and Registration)
4.4.2. Orientation and Movement
4.4.3. Sending and Receiving SMS
4
© 2022 e-Learning Centre, UCSC
4.1. Getting started with Android development
4.1.1. Introduction to Android development
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
5
© 2022 e-Learning Centre, UCSC
Android user interaction
6
© 2022 e-Learning Centre, UCSC
Android Software Developer Kit (SDK)
Publishing
7
© 2022 e-Learning Centre, UCSC
Android Platform Architecture
8
© 2022 e-Learning Centre, UCSC
• System apps have no special status
• System apps provide key capabilities to app developers
Example:
Your app can use a system app to deliver a SMS message.
10
© 2022 e-Learning Centre, UCSC
• Threading and low-level memory management
• Security features
• Drivers
11
© 2022 e-Learning Centre, UCSC
What is an Android app?
12
© 2022 e-Learning Centre, UCSC
Challenges of Android development
13
© 2022 e-Learning Centre, UCSC
4.1.1. Setting up the tools and environment
What is Android Studio?
Android Studio is the official Integrated Development Environment (IDE)
for Android app development. Android Studio offers even more features
that enhance your productivity when building Android apps, such as:
• A flexible Gradle-based build system
• A fast and feature-rich emulator
• A unified environment where you can develop for all Android devices
• Apply Changes to push code and resource changes to your running
app without restarting your app
• Code templates and GitHub integration to help you build common app
features and import sample code
• Extensive testing tools and frameworks
• Lint tools to catch performance, usability, version compatibility, and
other problems
• C++ and NDK support
14
© 2022 e-Learning Centre, UCSC
Installation Overview
15
© 2022 e-Learning Centre, UCSC
Name an activity
● Good practice:
○ Name main activity MainActivity
○ Name layout activity_main
● Use AppCompat
● Generating layout file is convenient
16
© 2022 e-Learning Centre, UCSC
Project folders
17
© 2022 e-Learning Centre, UCSC
Gradle build system
18
© 2022 e-Learning Centre, UCSC
Run your app on a device
1. Run
2. Select virtual
or physical
device
3. OK
19
© 2022 e-Learning Centre, UCSC
Run on a physical device
Windows drivers:
OEM USB Drivers
20
© 2022 e-Learning Centre, UCSC
Get feedback as your app runs
1. Emulator
running the
app
2. Run pane
3. Run tab to
open or
close the
Run pane
21
© 2022 e-Learning Centre, UCSC
Adding logging to your app
1. Logcat tab to
show Logcat
pane
2. Log level menu
22
© 2022 e-Learning Centre, UCSC
4.2. Working with User Interfaces
4.2.1. App manifest and resources
Any app project must have an AndroidManifest.xml file at the
root of the project source set. The manifest file describes essential
information about your app to the Android build tools, the
Android operating system, and Google Play.
The manifest file is required to declare the following:
App components
For each app component that you create in your app, you must
declare a corresponding XML element in the manifest file:
24
© 2022 e-Learning Centre, UCSC
The name of your subclass must be specified with the name
attribute, using the full package designation. For example,
an Activity subclass can be declared as follows:
25
© 2022 e-Learning Centre, UCSC
Intent filters
In every case, the icon and label that are set in a parent element
become the default icon and label value for all child elements. For
example, the icon and label that are set in the <application>
element are the default icon and label for each of the app's
components (such as all activities).
The icon and label that are set in a component's <intent-filter> are
shown to the user whenever that component is presented as an
option to fulfill an intent. By default, this icon is inherited from
whichever icon is declared for the parent component, but you
might want to change the icon for an intent filter if it provides a
unique action that you'd like to better indicate in the chooser
dialog.
27
© 2022 e-Learning Centre, UCSC
Permissions
Your app can also protect its own components with permissions. It
can use any of the permissions that are defined by Android, as
listed in android.Manifest.permission, or a permission that's
declared in another app. Your app can also define its own
permissions. A new permission is declared with the <permission>
element.
28
© 2022 e-Learning Centre, UCSC
Device compatibility
The manifest file is also where you can declare what types of
hardware or software features your app requires, and thus, which
types of devices your app is compatible with. Google Play Store
does not allow your app to be installed on devices that don't
provide the features or system version that your app requires.
There are several manifest tags that define which devices your app
is compatible with. The following are just a couple of the most
common tags.
<uses-feature>
The <uses-feature> element allows you to declare hardware and
software features your app needs. For example, if your app cannot
achieve basic functionality on a device without a compass sensor,
you can declare the compass sensor as required with the following
manifest tag:
29
© 2022 e-Learning Centre, UCSC
<uses-sdk>
Each successive platform version often adds new APIs not available in the
previous version. To indicate the minimum version with which your app is
compatible, your manifest must include the <uses-sdk> tag and its
minSdkVersion attribute.
30
© 2022 e-Learning Centre, UCSC
File conventions
Elements
Only the <manifest> and <application> elements are required.
They each must occur only once. Most of the other elements can
occur zero or more times. However, some of them must be present
to make the manifest file useful.
All of the values are set through attributes, not as character data
within an element.
Elements at the same level are generally not ordered. For example,
the <activity>, <provider>, and <service> elements can be placed
in any order. There are two key exceptions to this rule:
• An <activity-alias> element must follow the <activity> for which it is
an alias.
• The <application> element must be the last element inside the
<manifest> element.
31
© 2022 e-Learning Centre, UCSC
Attributes
Technically, all attributes are optional. However, many attributes
must be specified so that an element can accomplish its purpose.
For truly optional attributes, the reference documentation
indicates the default values.
Except for some attributes of the root <manifest> element, all
attribute names begin with an android: prefix. For example,
android:alwaysRetainTaskState. Because the prefix is universal, the
documentation generally omits it when referring to attributes by
name.
32
© 2022 e-Learning Centre, UCSC
Resource values
Some attributes have values that are displayed to users, such as
the title for an activity or your app icon. The value for these
attributes might differ based on the user's language or other
device configurations (such as to provide a different icon size
based on the device's pixel density), so the values should be set
from a resource or theme, instead of hard-coded into the manifest
file. The actual value can then change based on alternative
resources that you provide for different device configurations.
Resources are expressed as values with the following format:
"@[package:]type/name"
33
© 2022 e-Learning Centre, UCSC
The type is a type of resource, such as string or drawable, and the
name is the name that identifies the specific resource. Here is an
example:
34
© 2022 e-Learning Centre, UCSC
Providing alternative resources
Almost every app should provide alternative resources to support
specific device configurations
36
© 2022 e-Learning Centre, UCSC
4.2.2. Activities and Fragments
An activity is a single, focused thing that the user can do. Almost all
activities interact with the user, so the Activity class takes care of creating
a window for you in which you can place your UI with
setContentView(View). While activities are often presented to the user as
full-screen windows, they can also be used in other ways: as floating
windows (via a theme with R.attr.windowIsFloating set), Multi-Window
mode or embedded into other windows. There are two methods almost
all subclasses of Activity will implement:
38
© 2022 e-Learning Centre, UCSC
Implement new activities
39
© 2022 e-Learning Centre, UCSC
1. Define layout in XML
40
© 2022 e-Learning Centre, UCSC
2. Define Activity Java class
41
© 2022 e-Learning Centre, UCSC
3. Connect activity with layout
setContentView(R.layout.activity_main);
}
} Resource is layout in this XML file
42
© 2022 e-Learning Centre, UCSC
4. Declare activity in Android manifest
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
43
© 2022 e-Learning Centre, UCSC
Activity Lifecycle
44
© 2022 e-Learning Centre, UCSC
An activity has essentially four states:
• If an activity is in the foreground of the screen (at the highest
position of the topmost stack), it is active or running. This is usually
the activity that the user is currently interacting with.
• If an activity has lost focus but is still presented to the user, it is
visible. It is possible if a new non-full-sized or transparent activity has
focus on top of your activity, another activity has higher position in
multi-window mode, or the activity itself is not focusable in current
windowing mode. Such activity is completely alive (it maintains all
state and member information and remains attached to the window
manager).
• If an activity is completely obscured by another activity, it is
stopped or hidden. It still retains all state and member information,
however, it is no longer visible to the user so its window is hidden and
it will often be killed by the system when memory is needed
elsewhere.
• The system can drop the activity from memory by either asking it to
finish, or simply killing its process, making it destroyed. When it is
displayed again to the user, it must be completely restarted and
restored to its previous state.
45
© 2022 e-Learning Centre, UCSC
46
© 2022 e-Learning Centre, UCSC
Three key loops
•The entire lifetime of an activity happens between the first call
to onCreate(Bundle) through to a single final call to onDestroy().
An activity will do all setup of "global" state in onCreate(), and
release all remaining resources in onDestroy().
Views
If you look at your mobile device,
every user interface element that
you see is a View.
Views
Button CheckBox
EditText RadioButton
Slider Switch
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
49
© 2022 e-Learning Centre, UCSC
Android Studio layout editor
50
© 2022 e-Learning Centre, UCSC
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"
/>
51
© 2022 e-Learning Centre, UCSC
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"
52
© 2022 e-Learning Centre, UCSC
Create View in Java code
In an Activity: context
53
© 2022 e-Learning Centre, UCSC
ViewGroup and View hierarchy
ViewGroup contains "child" views
• ConstraintLayout: Positions UI elements using constraint
connections to other elements and to the layout edges
• ScrollView: Contains one element and enables scrolling
• RecyclerView: Contains a list of elements and enables
scrolling by adding and removing elements dynamically
Layouts
• are specific types of ViewGroups (subclasses of ViewGroup)
• contain child views
• can be in a row, column, grid, table, absolute
54
© 2022 e-Learning Centre, UCSC
Common Layout Classes
55
© 2022 e-Learning Centre, UCSC
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
56
© 2022 e-Learning Centre, UCSC
View hierarchy and screen layout
57
© 2022 e-Learning Centre, UCSC
Adapter
What is an Adapter
• Helps incompatible interfaces work together
• Example: Takes data from database Cursor and prepares
strings to put into a View
• Intermediary between data and View
• Manages creating, updating, adding, deleting View items as
underlying data changes
A primary toolbar within the activity that may display the activity
title, application-level navigation affordances, and other interactive
items.
From your activity, you can retrieve an instance of ActionBar by
calling getActionBar().
In some cases, the action bar may be overlayed by another bar that
enables contextual actions, using an ActionMode. For example,
when the user selects one or more items in your activity, you can
enable an action mode that offers actions specific to the selected
items, with a UI that temporarily replaces the action bar. Although
the UI may occupy the same space, the ActionMode APIs are
distinct and independent from those for ActionBar.
Refer. – ActionBar ,
Difference Between AppBar, ActionBar, and Toolbar in Android
59
© 2022 e-Learning Centre, UCSC
Dialogs
• AlertDialog
A dialog that can show a title, up to three
buttons, a list of selectable items, or a custom
layout.
• DatePickerDialog or TimePickerDialog
A dialog with a pre-defined UI that allows
the user to select a date or time.
60
© 2022 e-Learning Centre, UCSC
Creating a Dialog Fragment
61
© 2022 e-Learning Centre, UCSC
Building an Alert Dialog
62
© 2022 e-Learning Centre, UCSC
Notifications
63
© 2022 e-Learning Centre, UCSC
App icon badge
65
© 2022 e-Learning Centre, UCSC
Setting notification contents
66
© 2022 e-Learning Centre, UCSC
Tap action and Action buttons
67
© 2022 e-Learning Centre, UCSC
Pending intents
69
© 2022 e-Learning Centre, UCSC
Importance level
70
© 2022 e-Learning Centre, UCSC
Notification priority
setPriority(NotificationCompat.PRIORITY_HIGH)
Reference - LINK
71
© 2022 e-Learning Centre, UCSC
4.3. Data and App interaction
4.3.1. Intents and Broadcast Receivers
What is an intent?
Intent Action
Android
System
72
© 2022 e-Learning Centre, UCSC
What can intents do?
● Start an Activity
○ A button click starts a new Activity for text entry
○ Clicking Share opens an app that allows you to post a
photo
● Start an Service
○ Initiate downloading a file in the background
● Deliver Broadcast
○ The system informs everybody that the phone is now
charging
73
© 2022 e-Learning Centre, UCSC
Explicit and implicit intents
Explicit Intent
● Starts a specific Activity
○ Request tea with milk delivered by Nikita
○ Main activity starts the ViewShoppingCart Activity
Implicit Intent
● Asks system to find an Activity that can handle this
request
○ Find an open store that sells green tea
○ Clicking Share opens a chooser with a list of apps
1. Starting an activity
•An Activity represents a single screen in an app. You can start a
new instance of an Activity by passing an Intent to startActivity().
The Intent describes the activity to start and carries any necessary
data.
•If you want to receive a result from the activity when it finishes,
call startActivityForResult(). Your activity receives the result as a
separate Intent object in your activity's onActivityResult() callback.
For more information, see the Activities guide.
75
© 2022 e-Learning Centre, UCSC
2. Starting a service
•A Service is a component that performs operations in the
background without a user interface. With Android 5.0 (API level
21) and later, you can start a service with JobScheduler. For more
information about JobScheduler, see its API-reference
documentation.
•For versions earlier than Android 5.0 (API level 21), you can start
a service by using methods of the Service class. You can start a
service to perform a one-time operation (such as downloading a
file) by passing an Intent to startService(). The Intent describes
the service to start and carries any necessary data.
•If the service is designed with a client-server interface, you can
bind to the service from another component by passing
an Intent to bindService(). For more information, see
the Services guide.
76
© 2022 e-Learning Centre, UCSC
3. Delivering a broadcast
•A broadcast is a message that any app can receive. The system
delivers various broadcasts for system events, such as when the
system boots up or the device starts charging. You can deliver a
broadcast to other apps by passing
an Intent to sendBroadcast() or sendOrderedBroadcast().
78
© 2022 e-Learning Centre, UCSC
Register your broadcast receiver
79
© 2022 e-Learning Centre, UCSC
Receiving a system broadcast
● Starting from Android 8.0 (API level 26), static receivers can't
receive most of the system broadcasts.
● Use a dynamic receiver to register for these broadcasts.
● If you register for the system broadcasts in the manifest, the
Android system won't deliver them to your app.
● A few broadcasts, are excepted from this restriction. See the
complete list of implicit broadcast exceptions.
Reference – Implementation
80
© 2022 e-Learning Centre, UCSC
4.3.2. Preferences and Saving
81
© 2022 e-Learning Centre, UCSC
Shared Preferences vs. Saved Instance State
• Persist data across user sessions, even • Preserves state data across activity
if app is killed and restarted, or device instances in same user session
is rebooted
• Data that should not be
• Data that should be remembered remembered across sessions, such
across sessions, such as a user's as the currently selected tab or
preferred settings or their game score current state of activity.
• Common use is to store user • Common use is to recreate state
preferences after the device has been rotated
82
© 2022 e-Learning Centre, UCSC
Creating Shared Preferences
● SharedPreferences.Editor interface
● Takes care of all file operations
● put methods overwrite if key exists
● apply() saves asynchronously and safely
83
© 2022 e-Learning Centre, UCSC
Restoring Shared Preferences
Clearing
● Call clear() on the SharedPreferences.Editor and apply changes
● You can combine calls to put and clear. However, when you
apply(), clear() is always done first, regardless of order!
85
© 2022 e-Learning Centre, UCSC
The following LINKS describe content providers in more detail:
Content provider basics
How to access and update data using an existing content
provider.
Calendar provider
How to access the Calendar provider that is part of the
Android platform.
Contacts provider
How to access the Contacts provider that is part of the
Android platform.
86
© 2022 e-Learning Centre, UCSC
What is a service?
88
© 2022 e-Learning Centre, UCSC
Foreground services
Runs in the background but requires that the user is actively aware it
exists—e.g. music player using music service
• Higher priority than background services since user will notice its
absence—unlikely to be killed by the system
• Must provide a notification which the user cannot dismiss while the
service is running
89
© 2022 e-Learning Centre, UCSC
Creating a service
90
© 2022 e-Learning Centre, UCSC
Stopping a service
Reference – Guide
91
© 2022 e-Learning Centre, UCSC
4.3.4. AsyncTask and AsyncTaskLoader
Threads
92
© 2022 e-Learning Centre, UCSC
The Main thread must be fast
93
© 2022 e-Learning Centre, UCSC
Users uninstall unresponsive apps
94
© 2022 e-Learning Centre, UCSC
Background threads
● AsyncTask
● The Loader Framework
● Services
Worker Thread Do some work
95
© 2022 e-Learning Centre, UCSC
Two rules for Android threads
96
© 2022 e-Learning Centre, UCSC
What is AsyncTask?
Use AsyncTask to implement basic background tasks
Main Thread (UI Thread)
onPostExecute()
Worker Thread
doInBackground()
97
© 2022 e-Learning Centre, UCSC
AsyncTask helper methods
doInBackground()
● onPreExecute()
○ Runs on the main thread
○ Sets up the task
● onProgressUpdate()
○ Runs on the main thread
○ receives calls from publishProgress() from background
thread
98
© 2022 e-Learning Centre, UCSC
Creating an AsyncTask
1. Subclass AsyncTask
2. Provide data type sent to doInBackground()
3. Provide data type of progress units for onProgressUpdate()
4. Provide data type of result for onPostExecute()
private class MyAsyncTask
extends AsyncTask<URL, Integer, Bitmap> {...}
99
© 2022 e-Learning Centre, UCSC
MyAsyncTask class definition
doInBackground()
doInBackground()
onProgressUpdate()
onPostExecute()
doInBackground(
100
© 2022 e-Learning Centre, UCSC
When to use AsyncTask
Limitations of AsyncTask
102
© 2022 e-Learning Centre, UCSC
AsyncTaskLoader Overview
LoaderManager
Request Receive
Work Result
Activity
Reference – AsyncTaskLoader
103
© 2022 e-Learning Centre, UCSC
4.4. Sensors and Communication
4.4.1. Sensors (Sensor Identification and Registration)
Most Android-powered devices have built-in sensors that measure
motion, orientation, and various environmental conditions. These
sensors are capable of providing raw data with high precision and
accuracy, and are useful if you want to monitor three-dimensional
device movement or positioning, or you want to monitor changes
in the ambient environment near a device.
For example
A game might track readings from a device's gravity
sensor to infer complex user gestures and motions, such as tilt,
shake, rotation, or swing.
• Motion sensors
These sensors measure acceleration forces and rotational forces
along three axes. This category includes accelerometers, gravity
sensors, gyroscopes, and rotational vector sensors.
• Environmental sensors
These sensors measure various environmental parameters, such as
ambient air temperature and pressure, illumination, and humidity.
This category includes barometers, photometers, and
thermometers.
• Position sensors
These sensors measure the physical position of a device. This
category includes orientation sensors and magnetometers.
105
© 2022 e-Learning Centre, UCSC
Sensors
Motion sensors
• Accelerometers
• Gravity sensors
• Gyroscopes
• Rotational vector sensors
Environmental sensors
• Barometers
• Photometers (light sensors)
• Thermometers
Position sensors
• Magnetometers (geomagnetic field sensors)
• Proximity sensors
106
© 2022 e-Learning Centre, UCSC
Sensor Availability
107
© 2022 e-Learning Centre, UCSC
Android sensor framework
Sensor Manager
• Access and listen to sensors
• Register and unregister sensor event listeners
• Acquire orientation information
• Provides constants for accuracy, data acquisition rates, and
calibration
Framework Classes
• Sensor : Determine specific sensor's capabilities
• SensorEvent: Info about event, including raw sensor data
• SensorEventListener: Receives notifications about sensor
events
• When sensor has new data
• When sensor accuracy changes
108
© 2022 e-Learning Centre, UCSC
Reference Links –
109
© 2022 e-Learning Centre, UCSC
4.4.2. Orientation and Movement
The Android platform provides two sensors that let you determine
the position of a device: the geomagnetic field sensor and the
accelerometer.
The geomagnetic field sensor and the proximity sensor are
hardware-based. Most handset and tablet manufacturers include a
geomagnetic field sensor.
Likewise, handset manufacturers usually include a proximity sensor
to determine when a handset is being held close to a user's face
(for example, during a phone call).
For determining a device's orientation, you can use the readings
from the device's accelerometer and the geomagnetic field sensor.
110
© 2022 e-Learning Centre, UCSC
Compute the device's orientation
111
© 2022 e-Learning Centre, UCSC
Orientaion Angles
Azimuth (degrees of rotation about the -z axis). This is the angle
between the device's current compass direction and magnetic north. If the
top edge of the device faces magnetic north, the azimuth is 0 degrees; if
the top edge faces south, the azimuth is 180 degrees. Similarly, if the top
edge faces east, the azimuth is 90 degrees, and if the top edge faces west,
the azimuth is 270 degrees.
Pitch (degrees of rotation about the x axis). This is the angle between a
plane parallel to the device's screen and a plane parallel to the ground. If
you hold the device parallel to the ground with the bottom edge closest to
you and tilt the top edge of the device toward the ground, the pitch angle
becomes positive. Tilting in the opposite direction— moving the top edge
of the device away from the ground—causes the pitch angle to become
negative. The range of values is -180 degrees to 180 degrees.
Roll (degrees of rotation about the y axis). This is the angle between a
plane perpendicular to the device's screen and a plane perpendicular to
the ground. If you hold the device parallel to the ground with the bottom
edge closest to you and tilt the left edge of the device toward the ground,
the roll angle becomes positive. Tilting in the opposite direction—moving
the right edge of the device toward the ground— causes the roll angle to
become negative. The range of values is -90 degrees to 90 degrees.
112
© 2022 e-Learning Centre, UCSC
4.4.3. Sending and Receiving SMS
TELEPHONY
The Android telephony APIs let your applications access the
underlying telephone hardware stack, making it possible to create
your own dialer — or integrate call handling and phone state
monitoring into your applications.
Contains all text-based SMS messages in the SMS app inbox. You
can read messages and take appropriate actions like reading and
OTP and authenticate a user.
References –
Summary in Telephony
Telephony.Sms.Inbox
114
© 2022 e-Learning Centre, UCSC