SlideShare a Scribd company logo
1 of 84
COIT20270 Application Development for Mobile Platforms
Week 4: Designing UI’s with Views
Dr. R. Balsys, CQU, 2012.
Source: Beginning Android Programming with Android Studio,
J.F. DiMarzio, 2016
Week 4 – Designing UI’s with Views
Objectives, to understand how to use:
basic views
TextView views
Button, ImageButton, EditText, Checkbox, ToggleButton,
RadioButton and RadioGroup views
ProgressBar views
AutoCompleteTextView views
Picker views – TimePicker and DatePicker
CQU - COIT20270 Application Development for Mobile
Platforms
Basic Views
Basic views allow you to display text and perform selection.
This includes-
TextView
Button
ImageButton
EditText
Checkbox
ToggleButton
RadioButton
RadioGroup
CQU - COIT20270 Application Development for Mobile
Platforms
3
TextView view
This basic view allows you to display static text
<TextView> elements are contained in the main.xml file in the
res/layout directory
CQU - COIT20270 Application Development for Mobile
Platforms
4
Other Basic Views
Other basic views you will use include:
Button – a push button widget
ImageButton – a Button with an image on it
EditText – subclass of TextView with editable text
CheckBox – a button with checked and unchecked states
RadioGroup and RadioButton – RadioGroup is used to group
RadioButton’s
ToggleButton – displays states using a light indicator
CQU - COIT20270 Application Development for Mobile
Platforms
5
…Other Basic Views
Use “fill_parent” for android:layout_width or
android:layout_height so that the basic view fills the parent
view space
Use “wrap_content” for android:layout_width or
android:layout_height so that the basic view tightly bounds the
content only
The android:src value is used to define the image for an
ImageButton
You can use the style attribute to set the style of a CheckBox to
a star
RadioButtons in a RadioGroup automatically toggle off when
one is selected
CQU - COIT20270 Application Development for Mobile
Platforms
6
…Other Basic Views
Use android:orientation=“horizontal” to place RadioButtons
horizontally, rather than in the default vertical layout
The android:id of a view is used by View.findViewById() to
identify each unique view by its Id
The setOnClickListener() method is used to define a call-back
for handling a click on a view
CQU - COIT20270 Application Development for Mobile
Platforms
7
ProgressBar View
The ProgressBar view is used to indicate progress of some
background task
The default view is indeterminate, merely showing cyclic
animation, that you stop when the activity is complete
You hide a ProgressBar by setting its Visibility attribute to
View.Gone. This stops the ProgressBar and removes the it from
the view
You can change the look of the ProgressBar using the constants:
Widget.ProgressBar.Horizontal, Widget.ProgressBar.Small,
Widget.ProgressBar.Large, Widget.ProgressBar.Inverse,
Widget.ProgressBar.Small.Inverse,
Widget.ProgressBar.Large.Inverse
CQU - COIT20270 Application Development for Mobile
Platforms
8
AutoCompleteTextView
Is similar to EditText but it shows a list of suggestions to
complete the list automatically
You first create a list of Strings for the autocomplete
suggestions and use an ArrayAdapter object to manage the
strings
A simple_dropdown_item_1line constant is used to cause the
display of the strings 1 per line
The setThreshold() methods is used to determine how many
characters must be typed before the suggestions are displayed
CQU - COIT20270 Application Development for Mobile
Platforms
9
Picker Views - TimePicker
The TimePicker allows you to select the time of day in 24 hour
or AM/PM mode
By default it displays time in AM/PM mode. To use 24 hour
mode use the setIs24HourView() method
To programmatically get the time call the getCurrentHour() and
getCurrentMinute() methods
To display the time in a dialog use showDialog(id) with an id
for selecting a TimePickerDialog() method
The TimePickerDialog() method must be passed the current
context, hour, minute and a flag for the mode
When the Set button is clicked in the dialog the onTimeSet()
method is called and returns the values entered by the user
CQU - COIT20270 Application Development for Mobile
Platforms
Add screenshot from emulator
10
PickerViews - DatePicker
The DatePicker view allows the user to pick a particular date
You can call getDayOfMonth(), getMonth() and getYear()
methods to return the current day, month and year
When used in a dialog it works just like the TimePicker. The
onDateSet() method returns the selected day, month and year
values
CQU - COIT20270 Application Development for Mobile
Platforms
11
COIT13234 Mobile Software Development
Week 4: Designing UI’s with Views
Dr. R. Balsys, CQU, 2018.
Source: Beginning Android Programming with Android Studio,
Dimarzio, 2016.
Week 4 – Chapter 4: Enhancing Your Apps
Objectives, to :
use the ListView view
customise the ListView view
use the Spinner view
use ListFragment, DialogFragment and PreferenceFragment
CQU - COIT20270 Application Development for Mobile
Platforms
The ListView View
The ListView view displays a list of items as a vertical list
To use a ListView extend the ListActivity class
In the onCreate() method use the setListAdapter() method to
programmatically fill the ListView
The onListItemClick() method is fired when a list element is
clicked
theSetChoiceMode() method is used to customise the choices to
CHOICE_MODE_NONE, CHOICE_MODE_SINGLE or
CHOICE_MODE_MULTIPLE
The setTextFileFilterEnabled() method is used to filter choices
based on what text is typed. To find out which items are
checked used the isItemChecked() method
getItemAtPosition() method returns item at the position
CQU - COIT20270 Application Development for Mobile
Platforms
The SpinnerView
The SpinnerView displays one item at a time and lets the user
choose among them
The SpinnerView works much the same as the ListView with the
exception of the onNothingSelected() method which is fired
when the user pressing the back button which dismisses the
view
CQU - COIT20270 Application Development for Mobile
Platforms
Specialised Fragments
Fragments are used to dynamically customise the UI
Fragments are mini-activities with their own life-cycles
Three important Fragment sub-classes are the ListFragment,
DialogFragment and the PreferenceFragment
CQU - COIT20270 Application Development for Mobile
Platforms
ListFragment
The ListFragment displays a list of items from a data source
such as an array or Cursor
List fragments extend the ListFragment base class
In your onCreate() method you use setListAdapter() to fill the
list from the data source
The onListItemClick() method is called when a list element is
clicked
CQU - COIT20270 Application Development for Mobile
Platforms
DialogFragment
The DialogFragment floats on top of other fragments and is
modal
DialogFragments are used when you need a response from the
user before continuing
DialogFragments extend the DialogFragment base class
The newInstance() method allows a new instance of the
fragment to be created and displayed
The onCreateDialog() method is used to create the dialog and
show it by calling its show() method
You also need to implement doPositiveClick() and
doNegativeClick() to handle clicks on the OK and Cancel
buttons of the dialog
CQU - COIT20270 Application Development for Mobile
Platforms
PreferenceFragment
PreferenceFragment’s are used to allow the user to save
preferences for the application
You use a PreferenceActivity activity when working with
preferences
You must create a preferences.xml file and define the various
items that you want to persist in it
You load the preferences file in the preference fragment using
the addPreferencesFromResouce() method
Use the FragmentManager and FragmentTransaction classes to
display the preferences
CQU - COIT20270 Application Development for Mobile
Platforms
COIT20270 Application Development for Mobile Platforms
Week 11: Researching Mobile Systems
Dr. R. Balsys, CQU, 2018.
Week 11 – Research vs. Scholarship
Scholarship consists of collecting books and articles with view
to study or interpret the data, e.g. going to the library to study
information for an essay
Research is a process of inquiry that involves the purposeful,
systematic and rigorous collection, analysis and interpretation
of data to gain new knowledge
Research needs to be differentiated from scholarship
2
CQU - COIT20270 Application Development for Mobile
Platforms
Why study (a bit of) research in Mobile systems?
As with any new technology we must learn the pro’s and con’s
of the technology. To realistically determine these requires
application of the scientific method
To be able to critique a technology means we need to
understand philosophy so we can get to the meaning of things
It is common to use surveys or other instruments to gain
feedback or in usability studies, and mobile devices represent
an opportunity for this
3
CQU - COIT20270 Application Development for Mobile
Platforms
What is Science?
The Oxford dictionary defines science as:
The state of fact or knowing
Knowledge obtained by study
A particular branch of knowledge
There are two main ways of knowing:
Empiricism - which is through trust in the information gained
through the use of the senses
Rationalism – which is the use of the mind to infer relationships
and understanding
We need to introduce and define a group of words to help us
discuss the philosophy of the sciences
4
CQU - COIT20270 Application Development for Mobile
Platforms
4
Important terms- Philosophy
According to Bertrand Russel (1946) “Philosophy, as I
understand the word is something intermediate between
theology and science. Like theology, it consists of speculation
on matters as to which definite knowledge has, so far, been
unobtainable; but like science, it appeals to human reason rather
than authority. All definite knowledge – so I would contend –
belongs to science; all dogma belongs to theology. But between
science and theology lies a No Man’s Land, … this No Man’s
Land is philosophy”
Philosophy has three main branches; logic, metaphysics and
ethics
5
CQU - COIT20270 Application Development for Mobile
Platforms
5
Important terms- Metaphysics
Metaphysics is concerned with being and knowing, it can
explore the supra-sensible, it concerns itself with 1st principles,
concepts such as being, substance, essence, time, space,
causation etc.
Metaphysics has two main branches;
Ontology – the differentiation between the real and the
appearance, the assumptions underlying theories or systems of
ideas
Epistemology – is the theory of methods or grounds for
knowledge
6
CQU - COIT20270 Application Development for Mobile
Platforms
6
Important terms- Ethics and paradigm
Ethics is concerned with moral principles, what is right or
wrong, what ought to be done and what must not be done
According to Kuhn, 1970, “a paradigm can be considered a set
of ontological and epistemological assumptions, theories and
methods which a group of researchers accept and share as the
best way to develop knowledge”
7
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
7
Research Paradigms
Three research paradigms can be identified:
Logico-empirical paradigm – the traditional scientific method as
practiced in the natural sciences
Interpretive paradigm as practiced by some psychologists,
nurses and anthropologists
Critical paradigm which is research with the intent of political
empowerment and human emancipation
8
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
8
Historical Overview - Empiricism
The Greek philosophers Plato and Aristotle where the best
known philosophers from antiquity.
Copernicus, Galileo and Newton founded empiricism.
Empiricists believe that all knowledge is based on experience
and denies idealism that posits that the mind already has pre-
existing ideas and concepts
Famous empiricists include Newton (1642-1727), John Locke
(1632-1704) and David Hume (1711-1776). In the 19th century
Auguste Comte (1798-1857) and Charles Darwin (1855-1882)
where major proponents of empiricism
9
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
9
Historical Overview - Rationalism
In the 18th century Descartes, Spinoza and Leibniz developed
the rationalist tradition
Rationalism includes a belief that
By reason alone the nature of existence can be found
That knowledge forms a single system
That this system is deductible in character
That everything is understandable within this single system
10
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
10
…Historical Overview
Kant’s philosophy is recognised as a turning point for
philosophy. His position is that we construct knowledge by the
interaction of sense perceptions and judgment which makes
sense of the sense data
Hegel developed this to say that knowledge is discovered by the
contemplative faculty of the mind, the universe exists as a
complex whole (holism) and he rejects reductionism
Husserl founded phenomenology which involves suspending
assumed knowledge so that one is able to observe in an ideal,
disinterested scientific fashion and can questions ones own
beliefs and interpretations
11
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
11
Historical Overview – logico-empiricism
By the 1930’s a group called the Vienna Circle published a
manifesto that was later modified by Carl Popper and others
The central tenants are that there is a single reality out there;
science depends upon repeatable experiments; that theory and
empirical observations are separate entities; that causality is
linear in that event E can be deduced from initial conditions and
general laws; that reliable knowledge of a field or phenomena
reduces to particular instances or patterns of sensation; the goal
of positivist science is prediction and control of the physical or
social world and finally there is a need to demonstrate
reliability and repeatability of measurements
12
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
12
Logico-empiricism - Criticisms
A number of criticisms of logico-epiricism have been made
particularly the application of a single scientific method, that
facts and theories can be separated, and “facts” can prove our
theories
This lead to the development of post-positivism which takes
into account these criticisms, it no longer attempts to find
cause/effect relationships, but that rather truth is imperfect and
probabilistic
Post-positivists say there are no context free universal facts,
and whilst acknowledging that people cannot be totally
objective, they can be as objective as humanely possible
13
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
13
Interpretive/Constructivist & Critical Theory
Interpretive/Constructivist paradigm seeks answers about
meaning, about uncommon elements, it seeks to interpret the
observations
Critical theory provides guidelines to bring about change,
applies to humans and not things, and so is not predicable.
Theory is about a critique of power and relationships, about
determining the way forward by changing ideologies and power
relationships
14
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
14
A Model of the Research Process
Generally the research process follows a number of steps
Development of a theory
Develop testable ideas from the theory
Work out how to test the theory and devise a set of task to be
carried out to do this
Collection of the data
Interpret the results and reflect back on how these support or
otherwise the theory
15
CQU - COIT20270 Application Development for Mobile
Platforms
Research Types
Two broad approaches to research can be identified in the
literature – these are qualitative and quantitative research
Quantitative research implies quantitative data can be collected
and statistical relationships can be found
Qualitative research attempts to measure things where
interpretation is required, are usually qualified by words, not
numbers, and provide insights into possibilities
16
CQU - COIT20270 Application Development for Mobile
Platforms
16
COIT20270 Application Development for Mobile Platforms
Week 2: Activities, Fragments and Intents
Dr. R. Balsys, CQU, 2018.
Source: Beginning Android Programming with Android Studio,
J.F. DiMarzio, 2016
Week 2 – Activities, Fragments and Intents
Objectives to:
Understand Android activities and fragments
Use progress dialogs
Linking activities using intents
Resolving intent filter collisions
Returning results from an intent
Passing data using intent objects
CQU - COIT20270 Application Development for Mobile
Platforms
Understanding Activities
Activities extend the Activity base class
The Activity base class life cycle includes onCreate(), onStart(),
onResume(), onPause(), onStop(), onDestroy() and onRestart()
events
Figure 3-1 in DiMarzio text shows the life-cycle of an activity
and the stages it goes through
An activity usually occupies the whole screen but can behave as
a dialog by modifying the <Activity> element by adding
android:theme=“@android:style/Theme.Dialog” in the
AndroidManifest.xml file
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate Explain script functions
3
Adding Themes to an Activity
In Android 6 a new theme, Material, has been used for the
default look and feel
Use android:Theme=“@android:style/Theme.Material” in the
application tag of the android.manifest file to set this as the
default theme for the app
CQU - COIT20270 Application Development for Mobile
Platforms
Hiding the Activity Title and Displaying a Dialog Window
The activity title can be hidden by importing
android.view.Window and using
requestWindowFeature(Window,FEATURE_NO_TITLE) in the
onCreate() method
To display a dialog you implement the onCreateDialog() method
onCreateDialog() calls showDialog()that uses on integer to
select the actual dialog to display
The Hiding the Activity Title Try It Out shows you how to
display a dialog window when you need to get the user to
confirm an action
CQU - COIT20270 Application Development for Mobile
Platforms
Displaying a Progress Dialog
When an action will take more than 10 seconds a progress
dialog should be displayed
To create a progress dialog you create an instance of the
ProgressDialog class and call its show() method
An example is in the Displaying a Dialog section of the
DiMarzio text
You can also set properties such as a progress icon, title and
style. You also can add Cancel and OK buttons to the dialog
A more sophisticated version is given example is in the
Displaying a Progress Dialog section of the DiMarzio text
CQU - COIT20270 Application Development for Mobile
Platforms
Point out the (1,0) and (0,1) pixels to get the point home
6
Linking Activities Using Intents
Android applications can have more than 1 activity
Navigation between activities is achieved using intents
You add the name of the new class in the AndroidManifest.xml
file and give it a unique label
You supply an intent filter and set the category for the intent
filter as android.intent.category.DEFAULT
The DiMarzio text examples is in the Linking Activities with
Intents try it out.
CQU - COIT20270 Application Development for Mobile
Platforms
7
Resolving Intent Filter Collision
If more than two <intent-filter> elements have the same name
then when the application is run Android will present the user
with a list of choices to pick from
The chosen item becomes the default choice
To clear the default choice you have to go to the Application
Settings to clear the default choice
CQU - COIT20270 Application Development for Mobile
Platforms
Returning Results from an Intent
The startActivity() does not return data
If you need to return data from an Activity use the
startActivityForResult() method instead
The startActivityForResult() method has a second parameter
that returns a resultCode that identifies the activity being called
To return the value you need send the data back via the
setData() method
The setData() method calls a setResult() method to set the
resultCode
In the calling activity you implement the onActivityResult()
method to deal with the result
CQU - COIT20270 Application Development for Mobile
Platforms
Passing Data Using an Intent Object
Data is passed to an activity using an Intent object
The putExtra() method puts name:value pairs into an Intent
object
A Bundle object can also attach data to Intent objects using the
putExtra() method
To obtain the data in the Intent object use the getIntent()
method and call its getStringExtra() method to get the string
values using the putExtra() method
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
10
…Passing Data Using an Intent Object
To retrieve the Bundle object use the getExtras() method
Individual name:value pairs are retrieved using the appropriate
method, eg getString()
The data can also be retrieved using the setData() method
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
11
Week 2 – Mobilising Your Apps
Objectives, to:
Understand fragments
Adding fragments dynamically
Fragment lifestyle
Fragment interactions
Calling built-in applications using intents
Understand the intent object
Use intent filters
Adding categories
Displaying notifications
CQU - COIT20270 Application Development for Mobile
Platforms
Fragment
Fragments are contained within an Activity
Many Fragments can be contained within a single Activity
Fragments contain views that differ from one another
Fragments are a versatile way of of creating user interfaces for
Android applications
Fragments can be dynamically added or removed from
Activities
CQU - COIT20270 Application Development for Mobile
Platforms
…Fragments
The Java class for a Fragment extends Fragment
To draw the UI for a Fragment you over-ride the
onCreateView() method that returns a View object
In onCreateView() a LayoutInflater object inflates the UI from
an XML file
You add a fragment to an Activity with the <fragment> element
The <fragment> element uses unique id’s for the element using
the android:id or android:tag attributes
CQU - COIT20270 Application Development for Mobile
Platforms
Adding Fragments Dynamically
It is more useful to be able to add Fragments at run-time than by
configuring an XML file during design
You use the FragmentManager class to add fragments
Use the FragmentTransactions class to add, remove or replace
fragments
To ensure changes take place you call the commit() method on
your FragmentTransaction object
CQU - COIT20270 Application Development for Mobile
Platforms
Life Cycle of a Fragment
When a Fragment is being created it goes through onAttach(),
onCreate(), onCreateView() and onActivityCreated() states
When visible it goes through onStart() and onResume() states
When it goes into the background it goes through onPause() and
onStop() states
When the Fragment is destroyed it goes through onPause(),
onStop(), onDestroyView(), onDestroy() and onDetatch() states
CQU - COIT20270 Application Development for Mobile
Platforms
…Life Cycle of a Fragment
When an Activity goes into the background it is placed into the
back stack allowing it to resume if the Back button is pressed
Fragments must be manually placed in the back stack by calling
the addToBackStack() method
CQU - COIT20270 Application Development for Mobile
Platforms
Interactions Between Fragments
Fragments need to communicate with one-another to be
effective
The activity to which a fragment belongs can be determined
using the getActivity() method
Fragment Views can be found using the findViewById() method
The example in the Interaction Between Fragments try it out of
the DiMarzio text demonstrates fragment interaction
CQU - COIT20270 Application Development for Mobile
Platforms
Calling Built-in Applications Using Fragments
Intents can be used to call other Android applications from
within a fragment
Intents are paired with action and data intents
The action and data pairs describe the operation to be performed
You create an Intent object and then pass action and data
arguments to the Intent
CQU - COIT20270 Application Development for Mobile
Platforms
The Intent Object
You can call another activity by passing its action to the
constructor of an Intent object
You can also create an Intent object by passing in an action
constant and data
For some Intents the data type is not needed, the MIME type is
set using setType()
Intent objects can also be set using a category which groups
activities into logical units for filtering
CQU - COIT20270 Application Development for Mobile
Platforms
Using Intent Filters
In order for an activity to invoke another activity requires the
use of an <intent-filter> in the AndroidManifest.xml file
If multiple actions match the intent-filter then a dialog appears
for the user to choose the correct one
A createChooser() method can be used to customise this dialog
and prevent a crash when no match is found
CQU - COIT20270 Application Development for Mobile
Platforms
Adding Categories
To add a category you must first define an <intent-filter> for
the category,
Eg. <category android:name=“abc.net.au/justin” />
You must also add the category using the addCategory() method
on an Intent instance
eg. Intent I = new (….);
i.addCategory(“abc.net.au/justin”);
CQU - COIT20270 Application Development for Mobile
Platforms
Displaying Notifications
The NotificationManager class is used to display persistent
messages in the navigation bar at the top of the device
To use notifications you first declare a new Intent that uses the
NotificationView.class
You also create a PendingIntent instance initialised using the
getActivity() method to set the PendingIntent’s context, request
code, intent and flags
You then obtain an instance of the NotificationManager class
and create an instance of the Notification class
CQU - COIT20270 Application Development for Mobile
Platforms
…Displaying Notifications
You then use the setLatestEventInfo() method on the
Notification instance to setup the notification and its response
You then call the notify() method on your NotificationManager
instance to display the notification
CQU - COIT20270 Application Development for Mobile
Platforms
Week 3 – The Android UI
Objectives, to understand:
the components of a screen
views and view groups
how to adapt to display orientation
how to anchor views
how to resize and reposition views and managing changes to
display orientation
how to persist state information during configuration changes
how to detect orientation changes
CQU - COIT20270 Application Development for Mobile
Platforms
The components of a Screen
An Android activity has its UI defined in an XML file, usually
Main.xml
The onCreate() method sets the content view based on this XML
file
The elements of the XML file are mapped to corresponding
Android GUI class elements and drawn
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
2
Views and ViewGroups
A View is an interface object that has an appearance on the
screen and derives from android.view.View
Views can be grouped into ViewGroups
The following ViewGroups are supported;
LinearLayout - single horizontal or vertical row
AbsoluteLayout - allows position of each of its children to be
specified
TableLayout - groups views into rows and columns
RelativeLayout - specifies how each child is laid out relative to
the others
FrameLayout - a placeholder (frame) used to display a single
view
ScrollView – a special FrameLayout that allows for scrolling of
its contained views
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
3
Adapting to Display Orientation
Smartphones and tablets can switch between portrait and
landscape layouts
When the device is rotated the view needs to be automatically
redrawn to fit the new layout
The onCreate() method is called when the device is reorientated
Views can be anchored to the four edges of the screen
Views can be resized to fit the new orientation
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
4
Anchoring Views
Anchoring is usually achieved using the RelativeLayout. The
following attributes can then be used to anchor the elements
layout_AlignParentLeft – aligns view to parents left
layout_AlignParentRight – aligns view to parents right
layout_AlignParentTop – aligns view to parents top
layout_AlignParentBottom – aligns view to parents bottom
Layout_centerVertical – centres the view vertically
Layout_centerHorizontal – centres the view horizontally
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
5
Resizing, Repositioning and Managing Changes to Orientation
A separate res/layout folder containing a file called layout-
land.xml is used to define the landscape orientation view and
the default res/layout main.xml file then defines the portrait
layout
Android uses state information to pick between the two layouts
dependent on the devices orientation
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
6
Persistent State Information During Configuration Changes
The onSaveInstanceState() method is called whenever an
activity is killed or put into the background and this method can
be used to save state data in a Bundle object
The onRestoreInstanceState() method is used to restore
previously saved Bundle object
The onRetainNonConfigurationInstance() method is more
general and can be used to save a general object
The getLastNonConfigurationInstance() method is then used to
restore the general object
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
7
Detecting Orientation Changes
The WindowManager class is used to detect orientation changes
during runtime
The WindowManager’s getDefaultDisplay() method returns a
Display object whose width and height fields can be used to
deduce the devices orientation
CQU - COIT20270 Application Development for Mobile
Platforms
Explain script functions
8
Week 3 – The Android UI
Objectives, to understand how to:
control the orientation of an activity
utilise the action bar
add and customise items in the action bar
create the UI programmatically
listen for UI notifications
CQU - COIT20270 Application Development for Mobile
Platforms
Controlling Orientation of an Activity
You can programmatically force a change of orientation using
setRequestOrientation()
Use ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE or
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to set
landscape or portrait orientations
You can also set the android:screenOrientation value to
“portrait” or “landscape” in the <activity> tag in the
AndroidManifest.xml file
CQU - COIT20270 Application Development for Mobile
Platforms
Utilising the Action bar
The Action bar displays an icon and a title on the top of the
display screen
To show the action bar add setSupportActionBar(toolBar) in
your onCreate() method
On the right of the action bar are optional action items (menus)
You can get access to the action bar at runtime by using
getActionBar()
You can show() and hide() the action bar
You can hide the action bar using an android:theme attribute but
then getActionBar() returns null
CQU - COIT20270 Application Development for Mobile
Platforms
Adding Action Bar Items
Action bar items are used to call commonly performed
operations in your application
The action bar adds action items when the
onCreateOptionsMenu() method is called
Within onCreateOptionsMenu() you call a CreateMenu() method
to add the items
To add the items you create a MenuItem instance and call your
Menu’s add() method
Items can optionally have an icon associated with them using
setIcon()
CQU - COIT20270 Application Development for Mobile
Platforms
…Adding Action Bar Items
When the menu is selected the onOptionsItemSelected() method
is called
This contains a MenuChoice() method that returns the choice
The parameter in MenuChoice() is used to determine what
choice is made and what action to take as a result
CQU - COIT20270 Application Development for Mobile
Platforms
Customising Items and Application Icon
Use SHOW_AS_ACTION_WITH_TEXT constant in
setShowAsAction() to put text alongside action items
To allow the application icon to be clickable pass true in the
action bars setDisplayHomeAsUpEnable(true) call
If so the application icon has been clicked you can check the
MenuChoice() items getItemId() to see if it’s android.R.id.home
To use a click on the application icon to return to the main
activity create an Intent object and set the
Intent.FLAG_ACTIVITY_CLEAR_TOP flag and then call
startActivity()
CQU - COIT20270 Application Development for Mobile
Platforms
Programmatically Creating the UI
Rather than defining the UI in XML files you can dynamically
define the UI at runtime
You have to duplicate the process carried in in the XML files
First you create a LayoutParams instance
You then create a layout, eg LinearLayout, and create and
instantiate its fields
TextView, Button and other UI widgets are created and added to
the layout
You then create any required LayoutParams object
Finally you add the layout object to the activity using
addContentView()
CQU - COIT20270 Application Development for Mobile
Platforms
Listening to UI Notifications
Common methods that can be over-ridden in you activity
include:
onKeyDown – key pressed and not handled elsewhere
onKeyUp – key released and not handled elsewhere
onMenuItemSelected – called when panels menu item selected
onMenuOpened – called when panel is opened by the user
CQU - COIT20270 Application Development for Mobile
Platforms
COIT20270 Application Development for Mobile Platforms
Week 7: SMS and email Messaging, Location Based Services
Dr. R. Balsys, CQU, 2018.
Source: Beginning Android Programming with Android Studio,
J.F. DiMarzio, 2016
Week 7 – SMS and email Messaging
This week we:
Send SMS messages programmatically
Use the built in messaging application in our app
Receive SMS messages programmatically
Send emails from our applications
2
CQU - COIT20270 Application Development for Mobile
Platforms
SMS Messaging
SMS messaging is a “killer app” for mobile phones
SMS messaging has billions of users in todays world
Being able to send and receive SMS messages within our
applications is an attractive proposition, e.g. tracker app
You can test SMS messaging on the simulator
3
CQU - COIT20270 Application Development for Mobile
Platforms
Switch to site and read through section. Do not follow any links
3
Sending SMS Messages Programmatically
You need to set <uses-permission
android:name=“android.permissions.SEND_SMS”/> in your
Android Manifest file
You create an instance of the SmsManager class. When
declaring the instance you must use the getDefault() method to
get a SmsManager object
The sendTextMessage() method on the SmsManager instance
object is used to send the message
4
CQU - COIT20270 Application Development for Mobile
Platforms
…sendTextMessage
sendTextMessage() has the following 5 parameters:
destinationAddress: phone number of recipient
scAddress: service Centre address or null for default
text: content of the SMS
sentIntent: pending intent to invoke when sent
deliveryIntent: pending intent to invoke when delivered
5
CQU - COIT20270 Application Development for Mobile
Platforms
Using Built-in SMS app
It is simple to invoke the built in SMS app from your app. When
the SMS message is sent you return to your app
Create a new Intent instance with new
Intent(android.content.Intent.ACTION-VIEW) as the
constructor
The putExtra() method can then be used to load the “address”,
“sms_body” and “text” fields of the SMS messenger app when it
loads
You must also set the MIME type of the message using
setType(“vnd.android-dir/mms-sms”)
The startActivity() method is invoked with the Intent instance
as parameter to start the messenger app when the setup is
complete
6
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate and Explain how it works
6
Receiving SMS Messages
You need to set <uses-permission
android:name=“android.permissions.RECEIVE_SMS”/> in your
Android Manifest file
Receiving SMS messages is done using a BroadcastReceiver
object which allows you to receive Intents using
sendBroadcast(), that allows you to handle an event raised by
another application
To handle the event you override the onReceive() method
The SMS message is contained in the 2nd parameter of
onReceive() (an Intent object)
7
CQU - COIT20270 Application Development for Mobile
Platforms
Explain how the files work
7
…Receiving SMS Messages
SMS messages are stored in an Object array in PDU format. The
message is split into 160 character sub-arrays
You extract the content using the static createFromPdu() method
of the SmsMessage class
The phone number of the sender is found by calling the
getOriginatingAddress() method and the body of the message is
found using getMessageBody()
BroadcastReceiver’s remain running even when your app is not
running and so can respond to events even when the app is not
running
8
CQU - COIT20270 Application Development for Mobile
Platforms
Explain how the files work
8
Preventing Messaging Apps from Receiving Messages
The default behavior is that your application and the built-in
SMS app get any messages
To prevent another application from receiving the message use
<intent-filter android:priority=“100”/>
<action android:name=
“android.provider.Telephony.SMS_RECEIVED” /></intent-
filter>
in your Android manifest file and call abortBroacast() in your
onReceive() event handler
This will permanently block all incoming SMS calls
9
CQU - COIT20270 Application Development for Mobile
Platforms
Explain how the files work
9
Updating Activities from BroadcastReceiver
To display an SMS message in a TextView of your activity class
you create a modified SMSReceiver class that listens for a new
Intent type to use for the application, eg
“MY_APP_RECEIVED”
Then you override the onReceive() method of your
BroadcastReceiver object to display the SMS in the TextView
You need to create an IntentFilter object so you can listen for
the Intent. This is done by adding your “MY_APP_RECEIVED”
parameter when you call addAction() on your new IntentFilter
instance
10
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate and Explain how the files work
10
…Updating Activities from BroadcastReceiver
You call registerReceiver() in onResume() and
unregisterReceiver() in onPause() so the message is only
updated when the Activity is running in the foreground
11
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate and Explain how the files work
11
If your activity is in the background when a message is received
it is possible to automatically bring it to the foreground to
display the message
Register your BroadcastReceiver in your activities onCreate()
instead of in onResume() and unregister it in your onDestroy()
event rather than the onPause() event
Then modify the onReceive() event using an Intent to bring the
activity to the foreground by calling Intent’s
setFlag(“Intent.FLAG_ACTIVITY_NEW_CLASS”) and then
stating your Intent’s instance using startActivity()
12
CQU - COIT20270 Application Development for Mobile
Platforms
Invoking Activities from BroadcastReceiver
Demonstrate and Explain how the files work
12
You also need to add the tag android:launchMode=“singleTask”
to the activity section of your Android manifest file. This
prevents a new instance of your application being launched
whenever a message is received
Using SMS messaging inside your app has various legal and
ethical considerations
Once your app is granted permission to send SMS’s the user
gets no further indication that messaging and associated costs
occur
13
CQU - COIT20270 Application Development for Mobile
Platforms
…Invoking Activities from BroadcastReceiver
Demonstrate and Explain how the files work
13
Sending E-Mail
The Gmail/email app lets you configure e-mail accounts using
POP3 or IMAP.
You can use the built-in app or send and receive e-mails
programmatically
You use an Intent object to do this. Use the setData() method on
your Intent instance variable and use Uri.parse(“mailto:”) as the
parameter
14
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate and Explain how the files work
14
Sending E-Mail
Then use putExtra() with parameters
Intent.EXTRA_EMAIL , array of strings containing recipients
addresses
Intent.EXTRA_CC, array of strings containing other recipients
addresses
Intent.EXTRA_SUBJECT, string for the subject field of e-mail
Intent.EXTRA_TEXT, string containing the message
Set the Intent message type to “message/fc822” using the Intent
setType() method
Call startActivity() with Intent.createChooser
(your_intent_instance, “Email’) as parameter
15
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate and Explain how the files work
15
Week 7 – Location Based Services
Objectives, to:
Display Google maps in your app, with pan and zoom control,
switching between views and to add markers to the maps
Getting address of locations tapped on a map
Performing geocoding and reverse geocoding
Getting geographical data using GPS, Cell-ID and Wi-Fi
Location monitor and build a location tracker app
16
CQU - COIT20270 Application Development for Mobile
Platforms
Location Based Services (LBS)
In recent times apps that take advantage of the current location
of the mobile device have become popular
Use of location along with readily accessible maps allow for the
integration of direction to the required service
Google maps integrates with the Android device allowing use of
Google map and other services
17
CQU - COIT20270 Application Development for Mobile
Platforms
Displaying Maps
Google Maps comes bundle with the Android system
The textbook is out of date – we will be using Google Maps
Android API v2
For up-to-date instructions on creating the project and obtaining
the Maps API key see this weeks Lecture/Tutorial
The material in chapter 9 of the Lee text will only work if you
have a real Android phone (v4 or later) to test the code on,
otherwise you will need to create an Android Virtual device as
described in the Lecture/Tutorial. The default display now
shows the Zoom control automatically
18
CQU - COIT20270 Application Development for Mobile
Platforms
Changing Views
You can display Google maps in either maps view or satellite
view
In some countries (US, France, UK, Australia and Canada) it is
possible to display traffic conditions on the map in major cities
Green reflects smooth traffic flow, yellow moderate flow and
red indicates traffic congestion
19
CQU - COIT20270 Application Development for Mobile
Platforms
Navigating to a Specific Location and Adding Location Markers
You can programmatically navigate to a specific location in the
world
You can also place location markers at specific points on the
map
See this weeks Lecture/Tutorial for details
20
CQU - COIT20270 Application Development for Mobile
Platforms
Eclipse (with Android additions) should already be installed in
the labs, so these instructions are for installing on a students PC
20
Getting Touch Location
You can find the latitude and longitude of a location touched on
the display
From the latitude and longitude you can find the closest address
– a process known as reverse geocoding
See this weeks Lecture/Tutorial for details
21
CQU - COIT20270 Application Development for Mobile
Platforms
Getting location programmatically
See this weeks Lecture/Tutorial for details
22
CQU - COIT20270 Application Development for Mobile
Platforms
COIT20270 Application Development for Mobile Platforms
Week 5: Displaying Pictures and Menus, Data Persistence
Dr. R. Balsys, CQU, 2016.
Source: Beginning Android Programming with Android Studio,
J.F. DiMarzio, 2016
Week 5 – Displaying Pictures and Menus
Objectives, to :
use image views to display pictures
Use menu’s with views
Examine some additional views
2
CQU - COIT20270 Application Development for Mobile
Platforms
Using Image Views to Display Pictures
You display images with ImageView, Gallery, ImageSwitcher
and GridView views
An ImageView is used to display an individual image
The Gallery view displays images as a center-locked
horizontally scrolling list of images
The ImageSwitcher view is used when you wish to apply
animation or transitions when moving from one image to
another
The GridView shows images as a two dimensional array of rows
and columns of images
3
CQU - COIT20270 Application Development for Mobile
Platforms
Using Menu’s With Views
There are two main types of menus in Android
Options menu – activated using the keyboard Menu button and
it displays menus for the current activity
Context menu – displays information about the current view in
an activity when the user taps and holds on the view
The way menu’s are created and handled in Android 6 and
greater has changed and is different to that given in the text
4
CQU - COIT20270 Application Development for Mobile
Platforms
4
The Menu XML file
An XML defining the menu items is added as an XML file to
the projects res/menu folder
The menu items should be contained within
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
All menu items are defined within <item> </item> tags
As a minimum the item need the following options
android:id - identifier of the item
android:orderInCategory – the position of the item in the menu,
higher goes first
android:title – the text of the menu item
5
CQU - COIT20270 Application Development for Mobile
Platforms
5
The Menu Inflater
The onCreateOptionsMenu() is called when the Menu is drawn
Call getMenuInflater().inflate(R.menu.menu_main, menu);
and then return true;
You should replace menu_main with the name of the xml file
you created your menu resource in
6
CQU - COIT20270 Application Development for Mobile
Platforms
6
The onOptionsItemSelected method
The onCreateOptionsMenu() is called when the Menu is drawn
Call getMenuInflater().inflate(R.menu.menu_main, menu);
and then return true;
You should replace menu_main with the name of the xml file
you created your menu resource in
7
CQU - COIT20270 Application Development for Mobile
Platforms
7
Context Menu
To associate a context menu with a view you call the
setOnCreateContextMenuListener() on the view
The item to associate the context menu with uses the
setOnCreateContextMenuListener() to listen for any tap and
holds on the view
You override the onCreateContextMenu() method and call your
CreateMenu() method within it
8
CQU - COIT20270 Application Development for Mobile
Platforms
Get student to Google epistemological
8
Data Persistence
Objectives, to :
Save and load data with user preferences
Persist data to files
Create and use databases
9
CQU - COIT20270 Application Development for Mobile
Platforms
Saving and Loading User Preferences
To save data objects you can
Write the objects to a file
Save the object to a database
Use a SharedPreferences object
To use a SharedPreferences object you save a name/value pair
to SharedPreferences and this is then saved into an XML file for
you
10
CQU - COIT20270 Application Development for Mobile
Platforms
Accessing Preferences in an Activity
You 1st need to create a myapppreferences.xml file to use for
saving your data
Within this xml file you need to create key:value pairs for the
data you wish to save
Create an activity that extends the PreferenceActivity class and
call the addPreferencesFromResource() method to load the xml
file containing the preferences
11
CQU - COIT20270 Application Development for Mobile
Platforms
Retrieving and Modifying Preference Values
To make use of preferences you use the SharedPreferences class
The getSharedPreferences() method is used to get an instance of
the SharedPreferences class using the name of the XML
preferences file
You then create a SharedPreferences.Editor() object and use a
putString() method to change the value of a string preference
To save the change to the XML file you use the commit()
method
12
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the files working and discuss how they work
12
Changing the Default Name of a Preferences File
Using the PreferenceManager class you can call a
getPreferenceManager() method and then set the instance of this
to use a new name by calling the setSharedPreferenceName()
and passing in the new name
13
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
13
Persisting Data to Files
To store data to files use the java.io package
You can write data to the devices internal store by
Writing text to a file using the FileOutputStream class and the
openFileOutput() method with MODE_WORLD_READABLE
(public read access), MODE_PRIVATE (private access),
MODE_APPEND or MODE_WORLD_WRITEABLE (public
write access)
To convert a character stream to a byte stream create a
OutputStreamWriter instance using OutputStreamWriter() and
then use the write() method to write to the file. Remember to
flush() and close() the file
14
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
14
…Persisting Data to Files
You can read data from the devices internal store by
using the FileInputStream class and the openFileInput() passing
the file name as an input parameter. Then use the instance of the
FileInputStream to create a new InputStreamReader()
The input file is read in blocks of READ_BLOCK_SIZE bytes
into a character array buffer you create. The read() method is
used for this. read() returns -1 when the end of file is reached
15
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
15
Saving to External (SD card) Storage
Use the getExternalStorageDirectory() method to get a File
object that points to your SD card’s path
To write to the SD card you then create a new directory using
the previously found path using mkdirs()
You can then use the previously discussed FileOutputStream()
method to write objects to the file
16
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
16
…Saving to External (SD card) Storage
To load data from the SD card use the path and filename
approach used to write to the file and use a FileInputStream
object instance along with an InputStream instance to read from
the file
In order to write to a file you need to set the
WRITE_EXTERNAL_STORAGE permission in your
Android.Manifest file
17
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
17
Choosing a Storage Option
If you have data that can be represented using name:value pairs
then use the SharedPreferences approach to store your data
If your data is not in easily put into name:value pairs and is not
going to be shared with other apps then use internal storage to
save your data
If your data is to be shared with other apps or users then use the
SD card storage option
18
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
18
Using Static Resources
You can add files to your projects res/raw folder. These files
are then usable in your app
Use the getResources() method to return a Resources object to
get access to the file in res/raw
The resource ID is used to identify the required resource. It is
the name of the file in res/raw without its extension
19
CQU - COIT20270 Application Development for Mobile
Platforms
Creating and Using Databases
Using a relational database to store tables of data is efficient as
database queries can be used to retrieve the data
Android uses the SQLite database system to provide access to a
database, only to the app that created it
The created database is stored in the
/data/data/<package_name>/databases folder
20
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the files working and discuss how they work
20
Creating a DBAdapter Helper Class
It is a good idea to create a helper class to create, open, close
and use a SQLite database
A database has a name, tables and columns
You need to create constants to name the fields of your database
The DATABASE_CREATE constant contains the SQL
statements for creating the table of the database
Within your DBAdapter class create a DatabaseHelper class that
extends SQLiteOpenHelper
21
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
21
…Creating a DBAdapter Helper Class
Override the onCreate() method to create the new database
Override the onUpgrade() method for use when the database is
upgraded
You then define methods to use for opening, closing and
adding, deleting or updating rows in the table
Android uses the Cursor class to return values from queries
ContentValues object is used to store name:value pairs using its
put() method
22
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
22
CRUD Operations on the Database
As an example we will look at adding contacts to the contacts
database
Use the DBAdapter class to create a new instance of the
DBAdapter class
To retrieve contacts in the contacts table use the
getAllContacts() method. This returns a Cursor object.
You can use the moveToFirst() and moveToNext() methods to
examine each contact in turn. The contact details are found by
calling DisplayContact() on the cursor object
23
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
23
…CRUD Operations on the Database
To retrieve a single contact use its ID and call the getContact()
method to get the details which is returned in a Cursor object
To update a contact call the updateContact() method passing the
ID as the 1st parameter
To delete a contact use the deleteContact() method with the
contact ID as the parameter
To upgrade a new database to a new one change the
DATABASE_VERSION field in the DBAdapter class to a
higher value than the old one. This deletes the old table, ready
for the new table to be created from an existing one or
otherwise
24
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
24
Pre-creating a Database
Often the database is pre-created at design time and used at run-
time
Tools are used to create the initial database, such as that at
sourceforge.net/projects/sqlitebrowser. This tool allows you to
visually create the fields for the database and populate the
fields with values
The database is copied into the assets folder of your project.
When the application is created you copy the database in the
assets folder into the /data/data/<project_name>/databases
folder if it does not already exist. You can then use it as before
25
CQU - COIT20270 Application Development for Mobile
Platforms
Demonstrate the file working and discuss how it works
25
COIT20270 Application Development for Mobile Platforms
Week 6: Content Providers
Dr. R. Balsys, CQU, 2018.
Source: Beginning Android Programming with Android Studio,
J.F. DiMarzio, 2016
Content Providers
Objectives, to :
share data in Android
use a content provider
CQU - COIT20270 Application Development for Mobile
Platforms
Content Providers
Content providers are the recommended way of sharing data in
Android application
Content providers provide a consistent interface programming
interface across all Android applications
Content providers provide much the same services as databases
– add, delete, query, edit
but can be stored as databases, files or over a network
Basic Android content providers include;
Browser – bookmarks, history, etc.
CallLog – missed calls, call details, etc.
Contacts – contact details from address book
MediaStore – for audio, video and images
Settings – device settings and preferences
CQU - COIT20270 Application Development for Mobile
Platforms
…Content Providers
A URI is used to query a content provider. Query strings always
have the form
content:// <authority> / <path> / <id>
where
authority– name of the content provider. For user defined
content providers it is the fully qualified name, eg
wrox.com.provider
path– specifies the content provider data path to the service
provided
id– specifies the actual record required
Eg. Content://contacts/people/4 the fourth person in the people
table of the devices contacts database
Table 8.1 in chapter 8 of the DiMarzio text gives further
examples
CQU - COIT20270 Application Development for Mobile
Platforms
Using a Content Provider
You must first specify the URI of the content provider
Uri myContacts = Uri.parse(“content://contacts/people/”);
Post Honeycomb devices use CursorLoader() to get a cursor
instance to the data, but does not block the application thread
The CursorAdapter object maps data from the source to the
destination variables. You set up an array of string, String[], for
the column variable and an int[] for the views
You then create a new instance of a SimpleCursorAdapter class
variable using the column and view values as parameters
Honeycomb and later requires the addition of a
FLAG_REGISTER_CONTENT_OBSERVER argument
You also need to set READ_CONTACTS permission in the
Android.manifest file
CQU - COIT20270 Application Development for Mobile
Platforms
Pre-defined Querystring Parameters
A number of pre-defined Query string constants are defined
including:
Browser.BOOKMARKS_URI
CallLog.CONTENT_URI
MediaStore.Images.Media.INTERNAL_CONTENT_URI
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
Settings.CONTENT_URI
Eg Uri contacts= ContactsContract.Contacts.CONTENT_URI;
If you want to retrieve the 1st setting use Uri settings=
ContentUris.withAppendedId(ContactsContract.Contacts.CONT
ENT_URI, 2);
CQU - COIT20270 Application Development for Mobile
Platforms
Printing Cursor objects
Create a method that takes the Cursor variable as input
Use the Cursor classes moveToFirst() and moveToNext() to
iterate through the items in the Cursor object
The ContactsContract.Contacts._ID field returns the ID of the
contact and the ContactsContract.Contacts.DISPLAY_NAME
returns the contacts name
Use ContactsContract.Contacts.HAS_PHONE_NUMBER to
determine if the contact has a phone number and then
ContactsContract.CommonDataKinds.Phone.NUMBER to access
the phone number
CQU - COIT20270 Application Development for Mobile
Platforms
Content Providers - Projections
The 3rd parameter of CursorLoader() returns the columns that
are returned by the query – this parameter is known as the
projection
You can set up an array to contain the columns you wish to
return from the data source and pass this as the projection
parameter
String[] projection= new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
CQU - COIT20270 Application Development for Mobile
Platforms
Content Providers - Filtering
The 4th and 5th parameters of CursorLoader() enable you to
make a WHERE clause enquiry
CursorLoader cL=new CursorLoader(this, contacts, projection,
ContactsContract.Contacts.DISPLAY_NAME” + “ LIKE ‘Ron’
”, null, null);
You can use the next parameter to supply a list strings to use
instead
CursorLoader cL=new CursorLoader(this, contacts, projection,
ContactsContract.Contacts.DISPLAY_NAME” + “ LIKE ? ”,
new String[] {“Ron”, “Mary”}, null);
CQU - COIT20270 Application Development for Mobile
Platforms
Content Providers - Sorting
The last parameter of CursorLoader() enables you to specify an
ORDER BY clause of a SQL query
CursorLoader cL=new CursorLoader(this, contacts, projection,
ContactsContract.Contacs.DISPLAY_NAME” + “ LIKE ? ”,
new String[] {“Ron”, “Mary”},
ContactsContract.Contacts.DISPLAY_NAME” + “ ASC ”);
CQU - COIT20270 Application Development for Mobile
Platforms
Creating Your Own Content Provider
To create your own content provider you provide a class that
extends the ContentProvider base class
You need to override the following methods;
getType() – to return the MIME type of the data for the URI
onCreate() – called when provider created
query() – receives a client request and returns a Cursor object
insert() – inserts a new record in the content provide
delete() – deletes records in the content provider
update() – updates a record in the content provider
You can store your data in the file system, a database, an XML
file or through a web service
CQU - COIT20270 Application Development for Mobile
Platforms
…Creating Your Own Content Provider
You then need to define a number of strings such as the
PROVIDER_NAME, CONTENT_URI, _ID, a UriMatcher
instance, and a SQLiteDatabase with its associated constants
The UriMatcher object is used to parse the content URI through
the ContentResolver
You write a SQLiteHelperDatabase class to help manage the
database
You then write the implementations for getType(), onCreate(),
query(), insert(), delete() and update()
Call notifyChange() of the ContentResolver after insert() and
delete()
Modify the Android.Manifest file by adding the <provider>
element
CQU - COIT20270 Application Development for Mobile
Platforms
Using Your Own Content Provider
You need to create an activity to test your content provider
To add to the provider create a ContentValues object and
populate it with the required values for your data object
If the ContentProvider is in the same package as your tester you
can directly reference the provider fields, otherwise you need to
specify the field names directly
For external packages you need to refer to the content URI
using a fully qualified URI
You should then write methods to display the contents of you
content provider and to test the update() and delete() methods
CQU - COIT20270 Application Development for Mobile
Platforms
COIT20270 Application Development for Mobile Platforms
Week 8: Networking
Dr. R. Balsys, CQU, 2018.
Source: Beginning Android Programming with Android Studio,
J.F. DiMarzio, 2016
Week 8 – Networking
This week we:
Connect to the web using HTTP
Use XML web services
Use Jason web services
2
CQU - COIT20270 Application Development for Mobile
Platforms
Using the HTTP web services
HTTP is used as the main protocol in the WWW
It is used in tasks such as downloading web pages, and binary
data such as images, sound and video
To use the HTTP protocol your app must set the uses
INTERNET permission in your Android manifest file
You use the OpenHttpConnection() method that takes an URL
string as parameter to open a connection to the specified URL
By opening an InputStream object you can download bytes from
the URL
3
CQU - COIT20270 Application Development for Mobile
Platforms
…Using the HTTP web services
You must set the connection method using setRequestMethod().
Usually you use the HTTP GET verb for this
When the connection is established a HTTP response code is
returned. If this is HTTP_OK then you can proceed to get the
data using getInputStream()
4
CQU - COIT20270 Application Development for Mobile
Platforms
Downloading Binary Data
To download an image from a web server you use the
synchronous DownloadImage() method. This returns a Bitmap
object. It does this by opening a HTTP connection to the URL
and uses the decodeStream() method of the BitmapFactory class
to decode the InputStream instance and return it as a Bitmap
Since Android 3.0 all synchronous tasks must be wrapped in the
AsyncTask class to prevent them from stalling the UI
You create a DownloadImageTask that extends
AsyncTask<String, Void, Bitmap>
5
CQU - COIT20270 Application Development for Mobile
Platforms
…Downloading Binary Data
In the DownloadImageTask class you define the methods
doInBackground() and onPostExecute()
In doInBackground() you call DownloadImage() to get the
bitmap
In onPostExecute() you display the image in your UI using a UI
element
You call your DownloadImageTask class by creating an instance
of it in onCreate() and then calling execute() on the instance,
passing a URL as the parameter
6
CQU - COIT20270 Application Development for Mobile
Platforms
…Downloading Binary Data
To read multiple images you modify the doInBackground()
method to use a for loop to loop through each of the URLs. As
each image is completed you call publishProgress() to give
feedback
An extra onProgressUpdate() method is defined in the
DownloadImageTask class to display the downloaded images
In onCreate() you pass multiple URLs as the parameters of the
execute() method
NOTE: On the emulator localhost refers to the emulator itself.
If getting images from your PC use your PCs IP address instead
of localhost or the files will not be found
7
CQU - COIT20270 Application Development for Mobile
Platforms
Downloading Text
In some circumstances you may wish to GET plain text files.
The text file is stored as a String on the device
To achieve this write a DownLoadText(URL) method that
returns the text file as a single String
You open a Http connection to an InputStream object. Then use
an InputStreamReader instance to a new InputStreamReader()
instantiated with your InputStream object
You read the incoming stream of bytes into character buffers
and append the incoming String copy of the buffer contents to
the final returned String
You create a subclass of AsyncTask to call
DownLoadText(URL) asynchronously as before
8
CQU - COIT20270 Application Development for Mobile
Platforms
Accessing Web Services using GET
Many Web services respond to a GET query with an XML file
We need to be able to connect to the web service and then parse
the contents of the XML file
For example consider a web service that returns the dictionary
definition of the word (eg
http://services.aonware.com/DictService/DictService.asmx?op=
word )
Here you need to establish the connection to the web service
and then parse the XML returned
9
CQU - COIT20270 Application Development for Mobile
Platforms
…Accessing Web Services using GET
Here we create a WordDefinition(String) method that returns
the XML file in a local String object. We wrap this in a subclass
of AsyncTask and call WordDefinition (String) asynchronously
Use OpenHttpConnection() and pass the request string as the
URL, remembering to use the required word at the end of the
string
You create a local instance of a Document object and use the
newInstance() method of the DocumentBuilderFactory class to
create a DocumentBuilderFactory instance
10
CQU - COIT20270 Application Development for Mobile
Platforms
…Accessing Web Services using GET
You also need a DocumentBuilder object defined and then you
can use your DocumentBuilderFactory instance to try and get a
valid DocumentBuilder object. You call the parse() method get
a Document object
The elements of the word definition are then found within the
<definition> tags in the Document object model (DOM)
11
CQU - COIT20270 Application Development for Mobile
Platforms
Consuming Jason Services
XML has a number of disadvantages:
Documents sizes get big as the complexity goes up and so costs
rise
Parsing the XML to extract the content of the message is CPU
intensive, requires the complete DOM to be stored locally as a
tree structure so is memory intensive
A more efficient representation scheme is to use JavaScript
object notation (JSON) to encode the information
12
CQU - COIT20270 Application Development for Mobile
Platforms
JASON
JavaScript Object Notation (JSON) is a data exchange format
for defining data structures
JSON is light-weight and easy to read and write
JASON objects are represented as “key”:”value” pairs enclosed
in {}’s, eg. {"a":"I", "b": ["d", "e", "f"], "c":{"a": 1000,
"b":["fred"]} }
13
CQU - COIT20270 Application Development for Mobile
Platforms
Consuming JSON Services
To consume JSON services you create a readJSONFeed()
method
This method connects to the specified URL and then reads the
response from the web service as a String
You call the readJSONFeed() method asynchronously using the
AsyncTask class
readJSONFeed() in called in the AsyncTask’s doInBackground()
method and the JSON String you fetch is passed into the
onPostExecute() method of the AsyncTask
14
CQU - COIT20270 Application Development for Mobile
Platforms
Go to the API and read through the entries
14
…Consuming JSON Services
To obtain the list of objects in the JSON String you pass the
JSON received into a JSONArray() constructor to get a local
JSONArray object representing the JSON data
You can then use the length() method to get the length of the
JSON array and get a JSONObject from the JSONArray using
the getJSONObject() method
To get the key:value pair from a JSON object you use
getString(), getInt(), getLong() or get Boolean()
15
CQU - COIT20270 Application Development for Mobile
Platforms
Go to the API and read through the entries
15
COIT20270 Application Development for Mobile Platforms
Week 9: Developing Android Services and App testing
Dr. R. Balsys, CQU, 2018.
Source: Beginning Android Programming with Android Studio,
J.F. DiMarzio, 2016 and
https://www.tutorialspoint.com/mobile_testing/mobile_testing_q
uick_guide.htm
Week 9 – Developing Services
Objectives, to:
To create an Android service that runs in the background
Perform long running tasks in threads
Perform repeated tasks in a service
Understand how activities and services communicate
Understand threading in Android
2
CQU - COIT20270 Application Development for Mobile
Platforms
Android Services
Services are tasks that run in the background without the need
for a UI, e.g playing background music or repeatedly polling for
the devices current location
To create a service you extend the Service base class and
override:
onBind(): binds the activity to the service
onStart(): used to do things when the service first starts
onDestroy(): called when the service terminates and is used to
clean up resources used by the service
3
CQU - COIT20270 Application Development for Mobile
Platforms
Go to the API and read through the entries
3
…Android Services
Services must be declared using the service tag, or an action tag
in your intent-filter section for services that are available to
other applications, in the Android manifest file
You start the service using the startServices() method
You stop a service by calling the stopService() method
4
CQU - COIT20270 Application Development for Mobile
Platforms
Go to the API and read through the entries
4
Performing Long Running Tasks
Long running tasks will stall your UI making your activity
unresponsive
For this reason long running tasks are put into a separate thread
so the main thread can keep running
You implement an inner class that extends the asynchronous
AsyncTask class without manually creating threads and handlers
5
CQU - COIT20270 Application Development for Mobile
Platforms
Go to the API and read through the entries
5
The AsyncTask Class
The AsyncTask class has three generic types URL, Integer and
Long
These type of parameters are passed to the doInBackground(),
onProgressUpdate() and onPostExecute() methods of the
AsyncTask class
doInBackground() accepts an array of String’s corresponding to
URL’s as its parameter. In this method you implement the long
running task. To report progress you call publishProgress()
method passing the Integer % complete
onProgressUpdate() connects to UI’s elements to show tasks
percentage complete
onPostExecute() takes the Long value returned by
doInBackground() when it completes as its parameter and is
used to take action when this happens
Call stopSelf() in onPostExecute() to terminate the Service or it
keeps running
6
CQU - COIT20270 Application Development for Mobile
Platforms
new Media is correct capitalisation for the constructor
6
Doing Repeated Tasks in a Service
You may want to use the Timer class to arrange for a service to
be run at set time intervals
The TimerTask class implements a Runnable interface and runs
on its own thread. Hence it does not have to extend the
AsyncTask class to be run in the background
7
CQU - COIT20270 Application Development for Mobile
Platforms
7
…Doing Repeated Tasks in a Service
To repeat the service in the class create a method in your
Service and in it use a Timer object and call its
scheduleAtFixedRate() method passing in a new TimerTask()
that implements a run() method as scheduleAtFixedRate()’s 1st
parameter, the delay before the 1st call of the run() method as
the 2nd parameter and the delay between successive calls in
milli-seconds as the 3rd parameter
Call your new method directly from the onStartCommand()
method of your Service
8
CQU - COIT20270 Application Development for Mobile
Platforms
8
Asynchronous Tasks on Separate Threads Using IntentService
The IntentService class makes it easy to create an asynchronous
task that terminates when completed
IntentService is based on the Service class and handles
asynchronous requests on demand
It is started like a normal service, executes on a separate worker
thread and terminates itself when completed
9
CQU - COIT20270 Application Development for Mobile
Platforms
9
…Asynchronous Tasks on Separate Threads Using IntentService
To use IntentService class you define a new class that extends
IntentService
You need to implement a constructor that calls the superclass
passing in a string to name the service
You also need to override the onHandleIntent() method to
specify the action the service is to take when executing on the
worker thread
When onHandleIntent() is finished the thread is terminated and
then service is automatically stopped
10
CQU - COIT20270 Application Development for Mobile
Platforms
10
Week 9 – Mobile App Testing
This week we:
Understand the importance of testing the the apps we develop
for mobile devices
Develop a methodology for testing mobile devices
Understand how to choose which mobile devices we should test
Discuss strategies for testing on a range of devices (including
emulators)
Look at developing a mobile device test plan
11
CQU - COIT20270 Application Development for Mobile
Platforms
The Importance of App testing
There is a lot of competition for application and services on
mobile devices
Testing ensures that your device functions as intended
If your app fails at some task, is poorly designed or is
unresponsive your customers will move on to something else
very quickly
The goal of testing is to determine the quality of the software –
does it work, does it function as intended and does it meet the
users needs
Failure means your customers will desert you for other suppliers
12
CQU - COIT20270 Application Development for Mobile
Platforms
Mobile Testing Methodology
Comprehensive testing is complicated and expensive
In Mobile apps use is often made of the WWW (even though it
does not have too) so account must be taken of this
Testing must not just be restricted to the mobile device but any
services or peripherals the app uses
13
CQU - COIT20270 Application Development for Mobile
Platforms
Note: The reading addresses testing mobile web sites rather than
mobile app testing. However, a lot of similarity occurs between
the two
13
…Mobile Testing Methodology
According to Wikipedia mobile application testing includes
Functional testing
Laboratory testing – of complete wireless network
Performance testing – undertaken under different conditions
Memory leakage – test apps memory management
Interrupt testing – how it handles interrupts such as battery
removal, notifications, incoming/outgoing calls, etc..
Usability testing
Installation testing in actual practice
Any certification testing required by customers
14
CQU - COIT20270 Application Development for Mobile
Platforms
Note: The reading addresses testing mobile web sites rather than
mobile app testing. However, a lot of similarity occurs between
the two
14
Choosing Devices to Test
Comprehensive testing targets multiple device models,
operating systems, mobile networks and possible browsers
It generally is not possible to test on every mobile device so a
reasonable subset must be chosen
The process to follow includes;
List all target devices
Organise devices by operating system and version
Organise devices by modality and input method
Choose the strongest and weakest from the list for testing
15
CQU - COIT20270 Application Development for Mobile
Platforms
Note: The reading addresses testing mobile web sites rather than
mobile app testing. However, a lot of similarity occurs between
the two
15
Strategies for Testing on Devices
The greatest issue is to acquire the range of devices needed for
testing
This can be done by
Purchasing the devices outright
Joining industry developer programs
Use the services of a commercial provider to test
Use device emulators for testing
16
CQU - COIT20270 Application Development for Mobile
Platforms
Note: The reading addresses testing mobile web sites rather than
mobile app testing. However, a lot of similarity occurs between
the two
16
Developer Programs and Emulators
All the major manufactures of mobile devices have developer
programs that you can join for a fee that may provide
discounted device purchases, you to rent or borrow devices
and/or access to virtual devices
Emulators are a relatively inexpensive alternate to real devices,
however these are not the real devices and problems or errors
can slip through the testing process
In particular gestures and touches do not emulate well
17
CQU - COIT20270 Application Development for Mobile
Platforms
Note: The reading addresses testing mobile web sites rather than
mobile app testing. However, a lot of similarity occurs between
the two
17
Develop a Mobile Test Plan
Start by writing a summary to describe the purpose of the app,
its use cases and how you plan to test the device
Review the list of devices, OS versions etc. you plan to test
Decide whether testing uses actual devices, emulators or both.
If using actual devices decide how the devices are to be
acquired
Write scripts to detail the tests to be undertaken on the devices
and carry out the tests
18
CQU - COIT20270 Application Development for Mobile
Platforms
Note: The reading addresses testing mobile web sites rather than
mobile app testing. However, a lot of similarity occurs between
the two
18
COIT20270 Application Development for Mobile Platforms
Week 10: App Stores and Marketing
Dr. R. Balsys, CQU, 2018.
Source: Beginning Mobile Application Development in the
Cloud, R. Rodger, 2012, ch. 13 pp. 435-441.
Week 10 – App Stores & Selling Your App
This week we:
Create icons & splash screens for Apps
Prepare screenshots and App metadata
Understand AppStore terms and conditions
Determine how to develop a marketing plan
Understand freelance work
Understand how to use apps for business promotion
Use both standard and guerilla marketing tactics
Learn about building communities around our apps
2
CQU - COIT20270 Application Development for Mobile
Platforms
Icons and Splash screens
Icons are visually associated with your app and need to be well
designed and aesthetically pleasing
They should be designed by a graphics designer and a number
of different sized .png images are required
You full app also requires a “splash” screen
Screenshots of the main screens of your app are required for
submission to Apple’s App Store and the Android marketplace
On Android you can get a screenshot by holding the Back key
and also holding the Home key down for a few seconds or by
taking a screenshot from the emulator
3
CQU - COIT20270 Application Development for Mobile
Platforms
App Metadata
When submitting an App to a store the following information is
required
A short textual description of the app
The category to which your app belongs
Keywords relevant to search results for the app
Supporting website address for the app
Any promotional graphics or video
A change log for the app
A content rating
The market geographical regions
4
CQU - COIT20270 Application Development for Mobile
Platforms
Working With the App Store
App must be submitted and accepted before they are available
Apps need to be digitally signed
The general business model is that the store receives 30% of
either the sales price or the subscription fee, to be paid every 30
days
In-app advertising revenue appears to be exempt from the terms
You need to read the terms and conditions that apply to the use
of both the Android Marketplace and Apple’s App Store
5
CQU - COIT20270 Application Development for Mobile
Platforms
Determining a Marketing Strategy
A number of questions need to be answered to define a
marketing strategy. Specifics include:
Demographics, what are the sex, ages and incomes of target
audience
Needs, what user need does the app fill?
Cost of promotion, how much will advertising cost relative to
the market size?
How will the app be used?
You need to test and verify that your answers are correct
6
CQU - COIT20270 Application Development for Mobile
Platforms
Building Apps for Other
Most likely you will be building apps for your employer or on a
contract basis for someone. You should build for success
Explain to clients the importance of usability, meeting app store
guidelines, common interface conventions, the economics of
cloud hosting, and how to launch and market the app
Make sure you have a documented contract for work, have
received a down-payment before starting and invoice your time
and costs as they occur
Offer fixed rate or standard time and materials day rates. The
fixed price should be about 50% extra to cover time blow-outs
in development
Offer a discount for early payment
7
CQU - COIT20270 Application Development for Mobile
Platforms
Promoting Your Business
A number of strategies can be used to promote your business
Subscription Based Services. Here the app is distributed for free
but a monthly subscription is charged for services. The key is
that the service must be of value to the customer or they will
not pay
Offering free versions of the app. These all limit the
functionality of the app. The idea is the user can get a feel for
the app. The fully featured app is then purchased
If your business already has a commercial presence then the app
can be promoted through those channels
Selling in-app Ads. If enough people use your app then selling
advertising space in the app can be a useful revenue stream
Premium services can be offered at a higher rate
In-app purchases. In this model the app is free or almost so,
revenue is gained by selling items, eg games offering magical
items for real $’s
Cross application apps are developed once but deployed across
multiple devices thus increasing market base and potential
revenue
8
CQU - COIT20270 Application Development for Mobile
Platforms
Selling Apps
You need to be clear on why you are developing apps and
whether you are building reputation or trying to make money
Coding plays a relatively small part in the time involved in
selling apps. Most of your time will be spent marketing the app
You need to set goals such as
What apps for what audience
How much income per month are you targeting
Only build what can be done. Plan for apps that take about a
month to develop
Consider how you will pay the bills before your income starts
turning up
Set timelines for the progress in 1st 3 months and stick to it
Use a spreadsheet to model all your expenses and expected
income
9
CQU - COIT20270 Application Development for Mobile
Platforms
Embracing Marketing
You need to understand marketing. If you want to make money
then your target demographic must be able to buy the app
You need to understand where your market goes to find
information and make sure your product information can be
found there
Each app must be continually updated and marketed
You must either develop 1 or 2 high value apps or, more likely,
develop a large number of less costly apps
10
CQU - COIT20270 Application Development for Mobile
Platforms
Marketing Tactics
There are a large number of apps out there, getting noticed is
hard
You need to keep track of every $ spent on an app and your time
spent on an app. Use a spreadsheet for this and convert your
time into dollars on a contracting basis. Monitor this on a
weekly basis and if an app does not pay then consider spending
your time elsewhere
Only advertise in arenas where you know you will get customers
from
Use real people to help you user test your ideas. From this
develop your marketing ideas
Plan your marketing campaign to last months, using advertising,
blogs and other means for this
11
CQU - COIT20270 Application Development for Mobile
Platforms
Standard Tactics
Create a website to go with your app. It allows you to market
and service your customers
Have a forum on the website and continuously mine the forum
for useful information
Use social forums to spread the message about your app
Create a mailing list forum for you app and use this to spread
marketing information
Develop promotional material for your app and use it. Use
different promotional material and track the effectiveness of it
Give your app to well known bloggers in the hope they will
write about it
You can use traditional media for advertising as well
Submit your apps to mobile app competitions
Provide a free lite version of your app
Price your app competitively
12
CQU - COIT20270 Application Development for Mobile
Platforms
Expensive Tactics
Advertise your apps on on app directory site where the ad will
be seen
You can target high readership content sites and or advertise
within other popular apps
Create a sustained media campaign targeting social media and
major content sites
Use an advertising agency to do the promotion for you
You can also use offline advertising such as radio, TV and
newspapers to advertise
13
CQU - COIT20270 Application Development for Mobile
Platforms
Guerilla Tactics
A young individual is unlikely to have much money to put into
advertising, so use non-traditional ways of getting your message
out
Build a community around your app. Forums where you actively
participate with your users is one way to do this
You can start a forum with your test users and encourage them
to bring their friends along
You can offer in-app rewards to people for helping marketing
your product
You can offer rewards to bug-hunters to find bugs in your code
Have a social media sharing page in your app users can use to
connect to social sites
14
CQU - COIT20270 Application Development for Mobile
Platforms
…Guerilla Tactics
Direct potential customers to the app websites where
screenshots, videos etc., can help them make the buy decision
Ignore piracy – pop up a “please buy” message occasionally to
encourage purchase
Try to develop a high value content blog for your app
Provide links to your apps and app website in your email
signature
15
CQU - COIT20270 Application Development for Mobile
Platforms
Assessment item 1— Portfolio
Due date: 11:50 pm AEST, Friday of week 12 Portfolio
Weighting: 20%
1 Length: Less than 50 MB
Objectives
This assessment item relates to the course learning outcomes
numbers 2, 3 and 5 as stated in
the online course profile.
Details
You are to submit a weekly portfolio submission, using Mahara,
for weeks 2 to 11 inclusive.
To access Mahara, click the "CQU Portfolio" link in the
Network Services block on the left-
hand side of the Moodle site. The weekly portfolios will
describe your understanding of the
topic for the week, with relevant references and resources
providing evidence of your
understanding.
You are to conduct a search of the internet on the topic for the
week. You should review the
items you find and select a minimum of 5 items and link them to
your portfolio. You are not
to upload files from the internet, as you do not own copyright,
and if you do, this will be
plagiarism. You are to use links to your items only. You may
include items from YouTube,
clips from lectures and/or tutorials, and your own work that you
produce in the tutorials. Your
portfolio should capture rich ideas, resources and innovative
practice around mobile app
development within the frame of the weekly topics.
You are to write a brief discussion for each week as to why you
chose the items you did, and
why you thought the items chosen are appropriate. Harvard
referencing format and citations
are to be used to substantiate your discussion.
Assessment Criteria
Each portfolio submission will be assessed against the
following criteria:
Criteria Marks/week
Summary of weekly topic 0.5
Resource descriptions 1
Number and justification/quality of
resources
0.5
Penalties
Total 2

More Related Content

Similar to COIT20270 Application Development for Mobile PlatformsWeek 4.docx

Mobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfMobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdf
AbdullahMunir32
 
行動App開發管理實務 unit2
行動App開發管理實務 unit2行動App開發管理實務 unit2
行動App開發管理實務 unit2
Xavier Yin
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
Prof. Erwin Globio
 

Similar to COIT20270 Application Development for Mobile PlatformsWeek 4.docx (20)

Learning Android Part 2/6
Learning Android Part 2/6Learning Android Part 2/6
Learning Android Part 2/6
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2"Android" mobilių programėlių kūrimo įvadas #2
"Android" mobilių programėlių kūrimo įvadas #2
 
Mobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdfMobile Application Development -Lecture 09 & 10.pdf
Mobile Application Development -Lecture 09 & 10.pdf
 
Android user interface design-chapter13
Android user interface design-chapter13Android user interface design-chapter13
Android user interface design-chapter13
 
Android Tutorial
Android TutorialAndroid Tutorial
Android Tutorial
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android Apps
 
Android app development
Android app developmentAndroid app development
Android app development
 
Introduction of Xcode
Introduction of XcodeIntroduction of Xcode
Introduction of Xcode
 
Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
 
Swift
SwiftSwift
Swift
 
Android App development III
Android App development IIIAndroid App development III
Android App development III
 
Android Application Development - Level 2
Android Application Development - Level 2Android Application Development - Level 2
Android Application Development - Level 2
 
行動App開發管理實務 unit2
行動App開發管理實務 unit2行動App開發管理實務 unit2
行動App開發管理實務 unit2
 
Android UI
Android UIAndroid UI
Android UI
 
Get an Android tutorial for beginners
Get an Android tutorial for beginnersGet an Android tutorial for beginners
Get an Android tutorial for beginners
 
Android - Day3.pptx
Android - Day3.pptxAndroid - Day3.pptx
Android - Day3.pptx
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
 

More from mary772

Coding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docx
Coding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docxCoding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docx
Coding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docx
mary772
 
CNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docx
CNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docxCNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docx
CNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docx
mary772
 
Cognitive and Language Development Milestones Picture Book[WLO .docx
Cognitive and Language Development Milestones Picture Book[WLO .docxCognitive and Language Development Milestones Picture Book[WLO .docx
Cognitive and Language Development Milestones Picture Book[WLO .docx
mary772
 
Codes of (un)dress and gender constructs from the Greek to t.docx
Codes of (un)dress and gender constructs from the Greek to t.docxCodes of (un)dress and gender constructs from the Greek to t.docx
Codes of (un)dress and gender constructs from the Greek to t.docx
mary772
 
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docxCoding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
mary772
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mary772
 
CoevolutionOver the ages, many species have become irremediably .docx
CoevolutionOver the ages, many species have become irremediably .docxCoevolutionOver the ages, many species have become irremediably .docx
CoevolutionOver the ages, many species have become irremediably .docx
mary772
 
Coding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docxCoding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docx
mary772
 
Codes of Ethics Guides Not Prescriptions A set of rules and di.docx
Codes of Ethics Guides Not Prescriptions A set of rules and di.docxCodes of Ethics Guides Not Prescriptions A set of rules and di.docx
Codes of Ethics Guides Not Prescriptions A set of rules and di.docx
mary772
 
Codecademy Monetizing a Movement 815-093 815-093 Codecademy.docx
Codecademy Monetizing a Movement 815-093 815-093 Codecademy.docxCodecademy Monetizing a Movement 815-093 815-093 Codecademy.docx
Codecademy Monetizing a Movement 815-093 815-093 Codecademy.docx
mary772
 
Code of Ethics for the Nutrition and Dietetics Pr.docx
Code of Ethics  for the Nutrition and Dietetics Pr.docxCode of Ethics  for the Nutrition and Dietetics Pr.docx
Code of Ethics for the Nutrition and Dietetics Pr.docx
mary772
 
Code of Ethics for Engineers 4. Engineers shall act .docx
Code of Ethics for Engineers 4. Engineers shall act .docxCode of Ethics for Engineers 4. Engineers shall act .docx
Code of Ethics for Engineers 4. Engineers shall act .docx
mary772
 
Coder Name Rebecca Oquendo .docx
Coder Name  Rebecca Oquendo                                    .docxCoder Name  Rebecca Oquendo                                    .docx
Coder Name Rebecca Oquendo .docx
mary772
 
Codes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docx
Codes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docxCodes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docx
Codes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docx
mary772
 
cocaine, conspiracy theories and the cia in central america by Craig.docx
cocaine, conspiracy theories and the cia in central america by Craig.docxcocaine, conspiracy theories and the cia in central america by Craig.docx
cocaine, conspiracy theories and the cia in central america by Craig.docx
mary772
 
Code of EthicsThe Code of Ethical Conduct and Statement of Com.docx
Code of EthicsThe Code of Ethical Conduct and Statement of Com.docxCode of EthicsThe Code of Ethical Conduct and Statement of Com.docx
Code of EthicsThe Code of Ethical Conduct and Statement of Com.docx
mary772
 

More from mary772 (20)

Coding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docx
Coding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docxCoding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docx
Coding NotesImproving Diagnosis By Jacquie zegan, CCS, w.docx
 
CNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docx
CNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docxCNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docx
CNL-521 Topic 3 Vargas Case StudyBob and Elizabeth arrive.docx
 
Cognitive and Language Development Milestones Picture Book[WLO .docx
Cognitive and Language Development Milestones Picture Book[WLO .docxCognitive and Language Development Milestones Picture Book[WLO .docx
Cognitive and Language Development Milestones Picture Book[WLO .docx
 
Codes of (un)dress and gender constructs from the Greek to t.docx
Codes of (un)dress and gender constructs from the Greek to t.docxCodes of (un)dress and gender constructs from the Greek to t.docx
Codes of (un)dress and gender constructs from the Greek to t.docx
 
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docxCoding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
Coding Assignment 3CSC 330 Advanced Data Structures, Spri.docx
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
CoevolutionOver the ages, many species have become irremediably .docx
CoevolutionOver the ages, many species have become irremediably .docxCoevolutionOver the ages, many species have become irremediably .docx
CoevolutionOver the ages, many species have become irremediably .docx
 
Coding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docxCoding Component (50)Weve provided you with an implementation .docx
Coding Component (50)Weve provided you with an implementation .docx
 
Codes of Ethics Guides Not Prescriptions A set of rules and di.docx
Codes of Ethics Guides Not Prescriptions A set of rules and di.docxCodes of Ethics Guides Not Prescriptions A set of rules and di.docx
Codes of Ethics Guides Not Prescriptions A set of rules and di.docx
 
Codecademy Monetizing a Movement 815-093 815-093 Codecademy.docx
Codecademy Monetizing a Movement 815-093 815-093 Codecademy.docxCodecademy Monetizing a Movement 815-093 815-093 Codecademy.docx
Codecademy Monetizing a Movement 815-093 815-093 Codecademy.docx
 
Code switching involves using 1 language or nonstandard versions of .docx
Code switching involves using 1 language or nonstandard versions of .docxCode switching involves using 1 language or nonstandard versions of .docx
Code switching involves using 1 language or nonstandard versions of .docx
 
Code of Ethics for the Nutrition and Dietetics Pr.docx
Code of Ethics  for the Nutrition and Dietetics Pr.docxCode of Ethics  for the Nutrition and Dietetics Pr.docx
Code of Ethics for the Nutrition and Dietetics Pr.docx
 
Code of Ethics for Engineers 4. Engineers shall act .docx
Code of Ethics for Engineers 4. Engineers shall act .docxCode of Ethics for Engineers 4. Engineers shall act .docx
Code of Ethics for Engineers 4. Engineers shall act .docx
 
Coder Name Rebecca Oquendo .docx
Coder Name  Rebecca Oquendo                                    .docxCoder Name  Rebecca Oquendo                                    .docx
Coder Name Rebecca Oquendo .docx
 
Codes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docx
Codes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docxCodes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docx
Codes of Ethical Conduct A Bottom-Up ApproachRonald Paul .docx
 
CNL-530 Topic 2 Sexual Response Cycle ChartMasters and John.docx
CNL-530 Topic 2 Sexual Response Cycle ChartMasters and John.docxCNL-530 Topic 2 Sexual Response Cycle ChartMasters and John.docx
CNL-530 Topic 2 Sexual Response Cycle ChartMasters and John.docx
 
Code#RE00200012002020MN2DGHEType of Service.docx
Code#RE00200012002020MN2DGHEType of Service.docxCode#RE00200012002020MN2DGHEType of Service.docx
Code#RE00200012002020MN2DGHEType of Service.docx
 
CODE OF ETHICSReview the following case study and address the qu.docx
CODE OF ETHICSReview the following case study and address the qu.docxCODE OF ETHICSReview the following case study and address the qu.docx
CODE OF ETHICSReview the following case study and address the qu.docx
 
cocaine, conspiracy theories and the cia in central america by Craig.docx
cocaine, conspiracy theories and the cia in central america by Craig.docxcocaine, conspiracy theories and the cia in central america by Craig.docx
cocaine, conspiracy theories and the cia in central america by Craig.docx
 
Code of EthicsThe Code of Ethical Conduct and Statement of Com.docx
Code of EthicsThe Code of Ethical Conduct and Statement of Com.docxCode of EthicsThe Code of Ethical Conduct and Statement of Com.docx
Code of EthicsThe Code of Ethical Conduct and Statement of Com.docx
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Recently uploaded (20)

Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

COIT20270 Application Development for Mobile PlatformsWeek 4.docx

  • 1. COIT20270 Application Development for Mobile Platforms Week 4: Designing UI’s with Views Dr. R. Balsys, CQU, 2012. Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016 Week 4 – Designing UI’s with Views Objectives, to understand how to use: basic views TextView views Button, ImageButton, EditText, Checkbox, ToggleButton, RadioButton and RadioGroup views ProgressBar views AutoCompleteTextView views Picker views – TimePicker and DatePicker CQU - COIT20270 Application Development for Mobile Platforms Basic Views Basic views allow you to display text and perform selection. This includes- TextView Button ImageButton EditText Checkbox ToggleButton RadioButton RadioGroup
  • 2. CQU - COIT20270 Application Development for Mobile Platforms 3 TextView view This basic view allows you to display static text <TextView> elements are contained in the main.xml file in the res/layout directory CQU - COIT20270 Application Development for Mobile Platforms 4 Other Basic Views Other basic views you will use include: Button – a push button widget ImageButton – a Button with an image on it EditText – subclass of TextView with editable text CheckBox – a button with checked and unchecked states RadioGroup and RadioButton – RadioGroup is used to group RadioButton’s ToggleButton – displays states using a light indicator CQU - COIT20270 Application Development for Mobile Platforms
  • 3. 5 …Other Basic Views Use “fill_parent” for android:layout_width or android:layout_height so that the basic view fills the parent view space Use “wrap_content” for android:layout_width or android:layout_height so that the basic view tightly bounds the content only The android:src value is used to define the image for an ImageButton You can use the style attribute to set the style of a CheckBox to a star RadioButtons in a RadioGroup automatically toggle off when one is selected CQU - COIT20270 Application Development for Mobile Platforms 6 …Other Basic Views Use android:orientation=“horizontal” to place RadioButtons horizontally, rather than in the default vertical layout The android:id of a view is used by View.findViewById() to identify each unique view by its Id The setOnClickListener() method is used to define a call-back for handling a click on a view
  • 4. CQU - COIT20270 Application Development for Mobile Platforms 7 ProgressBar View The ProgressBar view is used to indicate progress of some background task The default view is indeterminate, merely showing cyclic animation, that you stop when the activity is complete You hide a ProgressBar by setting its Visibility attribute to View.Gone. This stops the ProgressBar and removes the it from the view You can change the look of the ProgressBar using the constants: Widget.ProgressBar.Horizontal, Widget.ProgressBar.Small, Widget.ProgressBar.Large, Widget.ProgressBar.Inverse, Widget.ProgressBar.Small.Inverse, Widget.ProgressBar.Large.Inverse CQU - COIT20270 Application Development for Mobile Platforms 8 AutoCompleteTextView Is similar to EditText but it shows a list of suggestions to complete the list automatically You first create a list of Strings for the autocomplete suggestions and use an ArrayAdapter object to manage the strings
  • 5. A simple_dropdown_item_1line constant is used to cause the display of the strings 1 per line The setThreshold() methods is used to determine how many characters must be typed before the suggestions are displayed CQU - COIT20270 Application Development for Mobile Platforms 9 Picker Views - TimePicker The TimePicker allows you to select the time of day in 24 hour or AM/PM mode By default it displays time in AM/PM mode. To use 24 hour mode use the setIs24HourView() method To programmatically get the time call the getCurrentHour() and getCurrentMinute() methods To display the time in a dialog use showDialog(id) with an id for selecting a TimePickerDialog() method The TimePickerDialog() method must be passed the current context, hour, minute and a flag for the mode When the Set button is clicked in the dialog the onTimeSet() method is called and returns the values entered by the user CQU - COIT20270 Application Development for Mobile Platforms Add screenshot from emulator 10 PickerViews - DatePicker The DatePicker view allows the user to pick a particular date You can call getDayOfMonth(), getMonth() and getYear() methods to return the current day, month and year When used in a dialog it works just like the TimePicker. The
  • 6. onDateSet() method returns the selected day, month and year values CQU - COIT20270 Application Development for Mobile Platforms 11 COIT13234 Mobile Software Development Week 4: Designing UI’s with Views Dr. R. Balsys, CQU, 2018. Source: Beginning Android Programming with Android Studio, Dimarzio, 2016. Week 4 – Chapter 4: Enhancing Your Apps Objectives, to : use the ListView view customise the ListView view use the Spinner view use ListFragment, DialogFragment and PreferenceFragment CQU - COIT20270 Application Development for Mobile Platforms The ListView View The ListView view displays a list of items as a vertical list To use a ListView extend the ListActivity class In the onCreate() method use the setListAdapter() method to programmatically fill the ListView The onListItemClick() method is fired when a list element is clicked theSetChoiceMode() method is used to customise the choices to CHOICE_MODE_NONE, CHOICE_MODE_SINGLE or
  • 7. CHOICE_MODE_MULTIPLE The setTextFileFilterEnabled() method is used to filter choices based on what text is typed. To find out which items are checked used the isItemChecked() method getItemAtPosition() method returns item at the position CQU - COIT20270 Application Development for Mobile Platforms The SpinnerView The SpinnerView displays one item at a time and lets the user choose among them The SpinnerView works much the same as the ListView with the exception of the onNothingSelected() method which is fired when the user pressing the back button which dismisses the view CQU - COIT20270 Application Development for Mobile Platforms Specialised Fragments Fragments are used to dynamically customise the UI Fragments are mini-activities with their own life-cycles Three important Fragment sub-classes are the ListFragment, DialogFragment and the PreferenceFragment CQU - COIT20270 Application Development for Mobile Platforms ListFragment The ListFragment displays a list of items from a data source such as an array or Cursor List fragments extend the ListFragment base class In your onCreate() method you use setListAdapter() to fill the list from the data source
  • 8. The onListItemClick() method is called when a list element is clicked CQU - COIT20270 Application Development for Mobile Platforms DialogFragment The DialogFragment floats on top of other fragments and is modal DialogFragments are used when you need a response from the user before continuing DialogFragments extend the DialogFragment base class The newInstance() method allows a new instance of the fragment to be created and displayed The onCreateDialog() method is used to create the dialog and show it by calling its show() method You also need to implement doPositiveClick() and doNegativeClick() to handle clicks on the OK and Cancel buttons of the dialog CQU - COIT20270 Application Development for Mobile Platforms PreferenceFragment PreferenceFragment’s are used to allow the user to save preferences for the application You use a PreferenceActivity activity when working with preferences You must create a preferences.xml file and define the various items that you want to persist in it You load the preferences file in the preference fragment using the addPreferencesFromResouce() method Use the FragmentManager and FragmentTransaction classes to display the preferences
  • 9. CQU - COIT20270 Application Development for Mobile Platforms COIT20270 Application Development for Mobile Platforms Week 11: Researching Mobile Systems Dr. R. Balsys, CQU, 2018. Week 11 – Research vs. Scholarship Scholarship consists of collecting books and articles with view to study or interpret the data, e.g. going to the library to study information for an essay Research is a process of inquiry that involves the purposeful, systematic and rigorous collection, analysis and interpretation of data to gain new knowledge Research needs to be differentiated from scholarship 2 CQU - COIT20270 Application Development for Mobile Platforms Why study (a bit of) research in Mobile systems? As with any new technology we must learn the pro’s and con’s of the technology. To realistically determine these requires application of the scientific method To be able to critique a technology means we need to understand philosophy so we can get to the meaning of things It is common to use surveys or other instruments to gain feedback or in usability studies, and mobile devices represent an opportunity for this 3
  • 10. CQU - COIT20270 Application Development for Mobile Platforms What is Science? The Oxford dictionary defines science as: The state of fact or knowing Knowledge obtained by study A particular branch of knowledge There are two main ways of knowing: Empiricism - which is through trust in the information gained through the use of the senses Rationalism – which is the use of the mind to infer relationships and understanding We need to introduce and define a group of words to help us discuss the philosophy of the sciences 4 CQU - COIT20270 Application Development for Mobile Platforms 4 Important terms- Philosophy According to Bertrand Russel (1946) “Philosophy, as I understand the word is something intermediate between theology and science. Like theology, it consists of speculation on matters as to which definite knowledge has, so far, been unobtainable; but like science, it appeals to human reason rather than authority. All definite knowledge – so I would contend – belongs to science; all dogma belongs to theology. But between science and theology lies a No Man’s Land, … this No Man’s
  • 11. Land is philosophy” Philosophy has three main branches; logic, metaphysics and ethics 5 CQU - COIT20270 Application Development for Mobile Platforms 5 Important terms- Metaphysics Metaphysics is concerned with being and knowing, it can explore the supra-sensible, it concerns itself with 1st principles, concepts such as being, substance, essence, time, space, causation etc. Metaphysics has two main branches; Ontology – the differentiation between the real and the appearance, the assumptions underlying theories or systems of ideas Epistemology – is the theory of methods or grounds for knowledge 6 CQU - COIT20270 Application Development for Mobile Platforms 6 Important terms- Ethics and paradigm Ethics is concerned with moral principles, what is right or
  • 12. wrong, what ought to be done and what must not be done According to Kuhn, 1970, “a paradigm can be considered a set of ontological and epistemological assumptions, theories and methods which a group of researchers accept and share as the best way to develop knowledge” 7 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 7 Research Paradigms Three research paradigms can be identified: Logico-empirical paradigm – the traditional scientific method as practiced in the natural sciences Interpretive paradigm as practiced by some psychologists, nurses and anthropologists Critical paradigm which is research with the intent of political empowerment and human emancipation 8 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 8 Historical Overview - Empiricism The Greek philosophers Plato and Aristotle where the best
  • 13. known philosophers from antiquity. Copernicus, Galileo and Newton founded empiricism. Empiricists believe that all knowledge is based on experience and denies idealism that posits that the mind already has pre- existing ideas and concepts Famous empiricists include Newton (1642-1727), John Locke (1632-1704) and David Hume (1711-1776). In the 19th century Auguste Comte (1798-1857) and Charles Darwin (1855-1882) where major proponents of empiricism 9 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 9 Historical Overview - Rationalism In the 18th century Descartes, Spinoza and Leibniz developed the rationalist tradition Rationalism includes a belief that By reason alone the nature of existence can be found That knowledge forms a single system That this system is deductible in character That everything is understandable within this single system 10 CQU - COIT20270 Application Development for Mobile Platforms
  • 14. Get student to Google epistemological 10 …Historical Overview Kant’s philosophy is recognised as a turning point for philosophy. His position is that we construct knowledge by the interaction of sense perceptions and judgment which makes sense of the sense data Hegel developed this to say that knowledge is discovered by the contemplative faculty of the mind, the universe exists as a complex whole (holism) and he rejects reductionism Husserl founded phenomenology which involves suspending assumed knowledge so that one is able to observe in an ideal, disinterested scientific fashion and can questions ones own beliefs and interpretations 11 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 11 Historical Overview – logico-empiricism By the 1930’s a group called the Vienna Circle published a manifesto that was later modified by Carl Popper and others The central tenants are that there is a single reality out there; science depends upon repeatable experiments; that theory and empirical observations are separate entities; that causality is linear in that event E can be deduced from initial conditions and general laws; that reliable knowledge of a field or phenomena reduces to particular instances or patterns of sensation; the goal
  • 15. of positivist science is prediction and control of the physical or social world and finally there is a need to demonstrate reliability and repeatability of measurements 12 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 12 Logico-empiricism - Criticisms A number of criticisms of logico-epiricism have been made particularly the application of a single scientific method, that facts and theories can be separated, and “facts” can prove our theories This lead to the development of post-positivism which takes into account these criticisms, it no longer attempts to find cause/effect relationships, but that rather truth is imperfect and probabilistic Post-positivists say there are no context free universal facts, and whilst acknowledging that people cannot be totally objective, they can be as objective as humanely possible 13 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 13 Interpretive/Constructivist & Critical Theory
  • 16. Interpretive/Constructivist paradigm seeks answers about meaning, about uncommon elements, it seeks to interpret the observations Critical theory provides guidelines to bring about change, applies to humans and not things, and so is not predicable. Theory is about a critique of power and relationships, about determining the way forward by changing ideologies and power relationships 14 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 14 A Model of the Research Process Generally the research process follows a number of steps Development of a theory Develop testable ideas from the theory Work out how to test the theory and devise a set of task to be carried out to do this Collection of the data Interpret the results and reflect back on how these support or otherwise the theory 15 CQU - COIT20270 Application Development for Mobile Platforms Research Types Two broad approaches to research can be identified in the literature – these are qualitative and quantitative research Quantitative research implies quantitative data can be collected
  • 17. and statistical relationships can be found Qualitative research attempts to measure things where interpretation is required, are usually qualified by words, not numbers, and provide insights into possibilities 16 CQU - COIT20270 Application Development for Mobile Platforms 16 COIT20270 Application Development for Mobile Platforms Week 2: Activities, Fragments and Intents Dr. R. Balsys, CQU, 2018. Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016 Week 2 – Activities, Fragments and Intents Objectives to: Understand Android activities and fragments Use progress dialogs Linking activities using intents Resolving intent filter collisions Returning results from an intent Passing data using intent objects CQU - COIT20270 Application Development for Mobile Platforms Understanding Activities Activities extend the Activity base class
  • 18. The Activity base class life cycle includes onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy() and onRestart() events Figure 3-1 in DiMarzio text shows the life-cycle of an activity and the stages it goes through An activity usually occupies the whole screen but can behave as a dialog by modifying the <Activity> element by adding android:theme=“@android:style/Theme.Dialog” in the AndroidManifest.xml file CQU - COIT20270 Application Development for Mobile Platforms Demonstrate Explain script functions 3 Adding Themes to an Activity In Android 6 a new theme, Material, has been used for the default look and feel Use android:Theme=“@android:style/Theme.Material” in the application tag of the android.manifest file to set this as the default theme for the app CQU - COIT20270 Application Development for Mobile Platforms Hiding the Activity Title and Displaying a Dialog Window The activity title can be hidden by importing android.view.Window and using requestWindowFeature(Window,FEATURE_NO_TITLE) in the onCreate() method To display a dialog you implement the onCreateDialog() method onCreateDialog() calls showDialog()that uses on integer to select the actual dialog to display The Hiding the Activity Title Try It Out shows you how to
  • 19. display a dialog window when you need to get the user to confirm an action CQU - COIT20270 Application Development for Mobile Platforms Displaying a Progress Dialog When an action will take more than 10 seconds a progress dialog should be displayed To create a progress dialog you create an instance of the ProgressDialog class and call its show() method An example is in the Displaying a Dialog section of the DiMarzio text You can also set properties such as a progress icon, title and style. You also can add Cancel and OK buttons to the dialog A more sophisticated version is given example is in the Displaying a Progress Dialog section of the DiMarzio text CQU - COIT20270 Application Development for Mobile Platforms Point out the (1,0) and (0,1) pixels to get the point home 6 Linking Activities Using Intents Android applications can have more than 1 activity Navigation between activities is achieved using intents You add the name of the new class in the AndroidManifest.xml file and give it a unique label You supply an intent filter and set the category for the intent filter as android.intent.category.DEFAULT
  • 20. The DiMarzio text examples is in the Linking Activities with Intents try it out. CQU - COIT20270 Application Development for Mobile Platforms 7 Resolving Intent Filter Collision If more than two <intent-filter> elements have the same name then when the application is run Android will present the user with a list of choices to pick from The chosen item becomes the default choice To clear the default choice you have to go to the Application Settings to clear the default choice CQU - COIT20270 Application Development for Mobile Platforms Returning Results from an Intent The startActivity() does not return data If you need to return data from an Activity use the startActivityForResult() method instead The startActivityForResult() method has a second parameter that returns a resultCode that identifies the activity being called To return the value you need send the data back via the setData() method The setData() method calls a setResult() method to set the resultCode In the calling activity you implement the onActivityResult() method to deal with the result CQU - COIT20270 Application Development for Mobile Platforms
  • 21. Passing Data Using an Intent Object Data is passed to an activity using an Intent object The putExtra() method puts name:value pairs into an Intent object A Bundle object can also attach data to Intent objects using the putExtra() method To obtain the data in the Intent object use the getIntent() method and call its getStringExtra() method to get the string values using the putExtra() method CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 10 …Passing Data Using an Intent Object To retrieve the Bundle object use the getExtras() method Individual name:value pairs are retrieved using the appropriate method, eg getString() The data can also be retrieved using the setData() method CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 11 Week 2 – Mobilising Your Apps Objectives, to:
  • 22. Understand fragments Adding fragments dynamically Fragment lifestyle Fragment interactions Calling built-in applications using intents Understand the intent object Use intent filters Adding categories Displaying notifications CQU - COIT20270 Application Development for Mobile Platforms Fragment Fragments are contained within an Activity Many Fragments can be contained within a single Activity Fragments contain views that differ from one another Fragments are a versatile way of of creating user interfaces for Android applications Fragments can be dynamically added or removed from Activities CQU - COIT20270 Application Development for Mobile Platforms …Fragments The Java class for a Fragment extends Fragment To draw the UI for a Fragment you over-ride the onCreateView() method that returns a View object In onCreateView() a LayoutInflater object inflates the UI from an XML file You add a fragment to an Activity with the <fragment> element The <fragment> element uses unique id’s for the element using the android:id or android:tag attributes
  • 23. CQU - COIT20270 Application Development for Mobile Platforms Adding Fragments Dynamically It is more useful to be able to add Fragments at run-time than by configuring an XML file during design You use the FragmentManager class to add fragments Use the FragmentTransactions class to add, remove or replace fragments To ensure changes take place you call the commit() method on your FragmentTransaction object CQU - COIT20270 Application Development for Mobile Platforms Life Cycle of a Fragment When a Fragment is being created it goes through onAttach(), onCreate(), onCreateView() and onActivityCreated() states When visible it goes through onStart() and onResume() states When it goes into the background it goes through onPause() and onStop() states When the Fragment is destroyed it goes through onPause(), onStop(), onDestroyView(), onDestroy() and onDetatch() states CQU - COIT20270 Application Development for Mobile Platforms …Life Cycle of a Fragment When an Activity goes into the background it is placed into the back stack allowing it to resume if the Back button is pressed Fragments must be manually placed in the back stack by calling
  • 24. the addToBackStack() method CQU - COIT20270 Application Development for Mobile Platforms Interactions Between Fragments Fragments need to communicate with one-another to be effective The activity to which a fragment belongs can be determined using the getActivity() method Fragment Views can be found using the findViewById() method The example in the Interaction Between Fragments try it out of the DiMarzio text demonstrates fragment interaction CQU - COIT20270 Application Development for Mobile Platforms Calling Built-in Applications Using Fragments Intents can be used to call other Android applications from within a fragment Intents are paired with action and data intents The action and data pairs describe the operation to be performed You create an Intent object and then pass action and data arguments to the Intent CQU - COIT20270 Application Development for Mobile Platforms The Intent Object You can call another activity by passing its action to the constructor of an Intent object
  • 25. You can also create an Intent object by passing in an action constant and data For some Intents the data type is not needed, the MIME type is set using setType() Intent objects can also be set using a category which groups activities into logical units for filtering CQU - COIT20270 Application Development for Mobile Platforms Using Intent Filters In order for an activity to invoke another activity requires the use of an <intent-filter> in the AndroidManifest.xml file If multiple actions match the intent-filter then a dialog appears for the user to choose the correct one A createChooser() method can be used to customise this dialog and prevent a crash when no match is found CQU - COIT20270 Application Development for Mobile Platforms Adding Categories To add a category you must first define an <intent-filter> for the category, Eg. <category android:name=“abc.net.au/justin” /> You must also add the category using the addCategory() method on an Intent instance eg. Intent I = new (….); i.addCategory(“abc.net.au/justin”); CQU - COIT20270 Application Development for Mobile Platforms
  • 26. Displaying Notifications The NotificationManager class is used to display persistent messages in the navigation bar at the top of the device To use notifications you first declare a new Intent that uses the NotificationView.class You also create a PendingIntent instance initialised using the getActivity() method to set the PendingIntent’s context, request code, intent and flags You then obtain an instance of the NotificationManager class and create an instance of the Notification class CQU - COIT20270 Application Development for Mobile Platforms …Displaying Notifications You then use the setLatestEventInfo() method on the Notification instance to setup the notification and its response You then call the notify() method on your NotificationManager instance to display the notification CQU - COIT20270 Application Development for Mobile Platforms Week 3 – The Android UI Objectives, to understand: the components of a screen views and view groups how to adapt to display orientation how to anchor views how to resize and reposition views and managing changes to display orientation
  • 27. how to persist state information during configuration changes how to detect orientation changes CQU - COIT20270 Application Development for Mobile Platforms The components of a Screen An Android activity has its UI defined in an XML file, usually Main.xml The onCreate() method sets the content view based on this XML file The elements of the XML file are mapped to corresponding Android GUI class elements and drawn CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 2 Views and ViewGroups A View is an interface object that has an appearance on the screen and derives from android.view.View Views can be grouped into ViewGroups The following ViewGroups are supported; LinearLayout - single horizontal or vertical row AbsoluteLayout - allows position of each of its children to be specified TableLayout - groups views into rows and columns RelativeLayout - specifies how each child is laid out relative to the others FrameLayout - a placeholder (frame) used to display a single view
  • 28. ScrollView – a special FrameLayout that allows for scrolling of its contained views CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 3 Adapting to Display Orientation Smartphones and tablets can switch between portrait and landscape layouts When the device is rotated the view needs to be automatically redrawn to fit the new layout The onCreate() method is called when the device is reorientated Views can be anchored to the four edges of the screen Views can be resized to fit the new orientation CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 4 Anchoring Views Anchoring is usually achieved using the RelativeLayout. The following attributes can then be used to anchor the elements layout_AlignParentLeft – aligns view to parents left layout_AlignParentRight – aligns view to parents right
  • 29. layout_AlignParentTop – aligns view to parents top layout_AlignParentBottom – aligns view to parents bottom Layout_centerVertical – centres the view vertically Layout_centerHorizontal – centres the view horizontally CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 5 Resizing, Repositioning and Managing Changes to Orientation A separate res/layout folder containing a file called layout- land.xml is used to define the landscape orientation view and the default res/layout main.xml file then defines the portrait layout Android uses state information to pick between the two layouts dependent on the devices orientation CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 6 Persistent State Information During Configuration Changes The onSaveInstanceState() method is called whenever an activity is killed or put into the background and this method can be used to save state data in a Bundle object The onRestoreInstanceState() method is used to restore previously saved Bundle object The onRetainNonConfigurationInstance() method is more general and can be used to save a general object The getLastNonConfigurationInstance() method is then used to
  • 30. restore the general object CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 7 Detecting Orientation Changes The WindowManager class is used to detect orientation changes during runtime The WindowManager’s getDefaultDisplay() method returns a Display object whose width and height fields can be used to deduce the devices orientation CQU - COIT20270 Application Development for Mobile Platforms Explain script functions 8 Week 3 – The Android UI Objectives, to understand how to: control the orientation of an activity utilise the action bar add and customise items in the action bar create the UI programmatically listen for UI notifications CQU - COIT20270 Application Development for Mobile Platforms
  • 31. Controlling Orientation of an Activity You can programmatically force a change of orientation using setRequestOrientation() Use ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE or ActivityInfo.SCREEN_ORIENTATION_PORTRAIT to set landscape or portrait orientations You can also set the android:screenOrientation value to “portrait” or “landscape” in the <activity> tag in the AndroidManifest.xml file CQU - COIT20270 Application Development for Mobile Platforms Utilising the Action bar The Action bar displays an icon and a title on the top of the display screen To show the action bar add setSupportActionBar(toolBar) in your onCreate() method On the right of the action bar are optional action items (menus) You can get access to the action bar at runtime by using getActionBar() You can show() and hide() the action bar You can hide the action bar using an android:theme attribute but then getActionBar() returns null CQU - COIT20270 Application Development for Mobile Platforms Adding Action Bar Items Action bar items are used to call commonly performed operations in your application The action bar adds action items when the onCreateOptionsMenu() method is called Within onCreateOptionsMenu() you call a CreateMenu() method to add the items
  • 32. To add the items you create a MenuItem instance and call your Menu’s add() method Items can optionally have an icon associated with them using setIcon() CQU - COIT20270 Application Development for Mobile Platforms …Adding Action Bar Items When the menu is selected the onOptionsItemSelected() method is called This contains a MenuChoice() method that returns the choice The parameter in MenuChoice() is used to determine what choice is made and what action to take as a result CQU - COIT20270 Application Development for Mobile Platforms Customising Items and Application Icon Use SHOW_AS_ACTION_WITH_TEXT constant in setShowAsAction() to put text alongside action items To allow the application icon to be clickable pass true in the action bars setDisplayHomeAsUpEnable(true) call If so the application icon has been clicked you can check the MenuChoice() items getItemId() to see if it’s android.R.id.home To use a click on the application icon to return to the main activity create an Intent object and set the Intent.FLAG_ACTIVITY_CLEAR_TOP flag and then call startActivity() CQU - COIT20270 Application Development for Mobile Platforms Programmatically Creating the UI Rather than defining the UI in XML files you can dynamically define the UI at runtime
  • 33. You have to duplicate the process carried in in the XML files First you create a LayoutParams instance You then create a layout, eg LinearLayout, and create and instantiate its fields TextView, Button and other UI widgets are created and added to the layout You then create any required LayoutParams object Finally you add the layout object to the activity using addContentView() CQU - COIT20270 Application Development for Mobile Platforms Listening to UI Notifications Common methods that can be over-ridden in you activity include: onKeyDown – key pressed and not handled elsewhere onKeyUp – key released and not handled elsewhere onMenuItemSelected – called when panels menu item selected onMenuOpened – called when panel is opened by the user CQU - COIT20270 Application Development for Mobile Platforms COIT20270 Application Development for Mobile Platforms Week 7: SMS and email Messaging, Location Based Services Dr. R. Balsys, CQU, 2018. Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016 Week 7 – SMS and email Messaging This week we:
  • 34. Send SMS messages programmatically Use the built in messaging application in our app Receive SMS messages programmatically Send emails from our applications 2 CQU - COIT20270 Application Development for Mobile Platforms SMS Messaging SMS messaging is a “killer app” for mobile phones SMS messaging has billions of users in todays world Being able to send and receive SMS messages within our applications is an attractive proposition, e.g. tracker app You can test SMS messaging on the simulator 3 CQU - COIT20270 Application Development for Mobile Platforms Switch to site and read through section. Do not follow any links 3 Sending SMS Messages Programmatically You need to set <uses-permission android:name=“android.permissions.SEND_SMS”/> in your Android Manifest file You create an instance of the SmsManager class. When declaring the instance you must use the getDefault() method to get a SmsManager object The sendTextMessage() method on the SmsManager instance object is used to send the message 4
  • 35. CQU - COIT20270 Application Development for Mobile Platforms …sendTextMessage sendTextMessage() has the following 5 parameters: destinationAddress: phone number of recipient scAddress: service Centre address or null for default text: content of the SMS sentIntent: pending intent to invoke when sent deliveryIntent: pending intent to invoke when delivered 5 CQU - COIT20270 Application Development for Mobile Platforms Using Built-in SMS app It is simple to invoke the built in SMS app from your app. When the SMS message is sent you return to your app Create a new Intent instance with new Intent(android.content.Intent.ACTION-VIEW) as the constructor The putExtra() method can then be used to load the “address”, “sms_body” and “text” fields of the SMS messenger app when it loads You must also set the MIME type of the message using setType(“vnd.android-dir/mms-sms”) The startActivity() method is invoked with the Intent instance as parameter to start the messenger app when the setup is complete 6 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate and Explain how it works
  • 36. 6 Receiving SMS Messages You need to set <uses-permission android:name=“android.permissions.RECEIVE_SMS”/> in your Android Manifest file Receiving SMS messages is done using a BroadcastReceiver object which allows you to receive Intents using sendBroadcast(), that allows you to handle an event raised by another application To handle the event you override the onReceive() method The SMS message is contained in the 2nd parameter of onReceive() (an Intent object) 7 CQU - COIT20270 Application Development for Mobile Platforms Explain how the files work 7 …Receiving SMS Messages SMS messages are stored in an Object array in PDU format. The message is split into 160 character sub-arrays You extract the content using the static createFromPdu() method of the SmsMessage class The phone number of the sender is found by calling the getOriginatingAddress() method and the body of the message is found using getMessageBody() BroadcastReceiver’s remain running even when your app is not running and so can respond to events even when the app is not running 8 CQU - COIT20270 Application Development for Mobile Platforms
  • 37. Explain how the files work 8 Preventing Messaging Apps from Receiving Messages The default behavior is that your application and the built-in SMS app get any messages To prevent another application from receiving the message use <intent-filter android:priority=“100”/> <action android:name= “android.provider.Telephony.SMS_RECEIVED” /></intent- filter> in your Android manifest file and call abortBroacast() in your onReceive() event handler This will permanently block all incoming SMS calls 9 CQU - COIT20270 Application Development for Mobile Platforms Explain how the files work 9 Updating Activities from BroadcastReceiver To display an SMS message in a TextView of your activity class you create a modified SMSReceiver class that listens for a new Intent type to use for the application, eg “MY_APP_RECEIVED” Then you override the onReceive() method of your BroadcastReceiver object to display the SMS in the TextView You need to create an IntentFilter object so you can listen for the Intent. This is done by adding your “MY_APP_RECEIVED” parameter when you call addAction() on your new IntentFilter instance
  • 38. 10 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate and Explain how the files work 10 …Updating Activities from BroadcastReceiver You call registerReceiver() in onResume() and unregisterReceiver() in onPause() so the message is only updated when the Activity is running in the foreground 11 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate and Explain how the files work 11 If your activity is in the background when a message is received it is possible to automatically bring it to the foreground to display the message Register your BroadcastReceiver in your activities onCreate() instead of in onResume() and unregister it in your onDestroy() event rather than the onPause() event Then modify the onReceive() event using an Intent to bring the activity to the foreground by calling Intent’s setFlag(“Intent.FLAG_ACTIVITY_NEW_CLASS”) and then stating your Intent’s instance using startActivity() 12 CQU - COIT20270 Application Development for Mobile Platforms Invoking Activities from BroadcastReceiver
  • 39. Demonstrate and Explain how the files work 12 You also need to add the tag android:launchMode=“singleTask” to the activity section of your Android manifest file. This prevents a new instance of your application being launched whenever a message is received Using SMS messaging inside your app has various legal and ethical considerations Once your app is granted permission to send SMS’s the user gets no further indication that messaging and associated costs occur 13 CQU - COIT20270 Application Development for Mobile Platforms …Invoking Activities from BroadcastReceiver Demonstrate and Explain how the files work 13 Sending E-Mail The Gmail/email app lets you configure e-mail accounts using POP3 or IMAP. You can use the built-in app or send and receive e-mails programmatically You use an Intent object to do this. Use the setData() method on your Intent instance variable and use Uri.parse(“mailto:”) as the parameter 14 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate and Explain how the files work
  • 40. 14 Sending E-Mail Then use putExtra() with parameters Intent.EXTRA_EMAIL , array of strings containing recipients addresses Intent.EXTRA_CC, array of strings containing other recipients addresses Intent.EXTRA_SUBJECT, string for the subject field of e-mail Intent.EXTRA_TEXT, string containing the message Set the Intent message type to “message/fc822” using the Intent setType() method Call startActivity() with Intent.createChooser (your_intent_instance, “Email’) as parameter 15 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate and Explain how the files work 15 Week 7 – Location Based Services Objectives, to: Display Google maps in your app, with pan and zoom control, switching between views and to add markers to the maps Getting address of locations tapped on a map Performing geocoding and reverse geocoding Getting geographical data using GPS, Cell-ID and Wi-Fi Location monitor and build a location tracker app 16 CQU - COIT20270 Application Development for Mobile Platforms
  • 41. Location Based Services (LBS) In recent times apps that take advantage of the current location of the mobile device have become popular Use of location along with readily accessible maps allow for the integration of direction to the required service Google maps integrates with the Android device allowing use of Google map and other services 17 CQU - COIT20270 Application Development for Mobile Platforms Displaying Maps Google Maps comes bundle with the Android system The textbook is out of date – we will be using Google Maps Android API v2 For up-to-date instructions on creating the project and obtaining the Maps API key see this weeks Lecture/Tutorial The material in chapter 9 of the Lee text will only work if you have a real Android phone (v4 or later) to test the code on, otherwise you will need to create an Android Virtual device as described in the Lecture/Tutorial. The default display now shows the Zoom control automatically 18 CQU - COIT20270 Application Development for Mobile Platforms Changing Views You can display Google maps in either maps view or satellite view In some countries (US, France, UK, Australia and Canada) it is possible to display traffic conditions on the map in major cities
  • 42. Green reflects smooth traffic flow, yellow moderate flow and red indicates traffic congestion 19 CQU - COIT20270 Application Development for Mobile Platforms Navigating to a Specific Location and Adding Location Markers You can programmatically navigate to a specific location in the world You can also place location markers at specific points on the map See this weeks Lecture/Tutorial for details 20 CQU - COIT20270 Application Development for Mobile Platforms Eclipse (with Android additions) should already be installed in the labs, so these instructions are for installing on a students PC 20 Getting Touch Location You can find the latitude and longitude of a location touched on the display From the latitude and longitude you can find the closest address – a process known as reverse geocoding See this weeks Lecture/Tutorial for details 21 CQU - COIT20270 Application Development for Mobile Platforms Getting location programmatically
  • 43. See this weeks Lecture/Tutorial for details 22 CQU - COIT20270 Application Development for Mobile Platforms COIT20270 Application Development for Mobile Platforms Week 5: Displaying Pictures and Menus, Data Persistence Dr. R. Balsys, CQU, 2016. Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016 Week 5 – Displaying Pictures and Menus Objectives, to : use image views to display pictures Use menu’s with views Examine some additional views 2 CQU - COIT20270 Application Development for Mobile Platforms Using Image Views to Display Pictures You display images with ImageView, Gallery, ImageSwitcher and GridView views An ImageView is used to display an individual image The Gallery view displays images as a center-locked horizontally scrolling list of images The ImageSwitcher view is used when you wish to apply animation or transitions when moving from one image to another The GridView shows images as a two dimensional array of rows and columns of images
  • 44. 3 CQU - COIT20270 Application Development for Mobile Platforms Using Menu’s With Views There are two main types of menus in Android Options menu – activated using the keyboard Menu button and it displays menus for the current activity Context menu – displays information about the current view in an activity when the user taps and holds on the view The way menu’s are created and handled in Android 6 and greater has changed and is different to that given in the text 4 CQU - COIT20270 Application Development for Mobile Platforms 4 The Menu XML file An XML defining the menu items is added as an XML file to the projects res/menu folder The menu items should be contained within <menu xmlns:android="http://schemas.android.com/apk/res/android"> </menu> All menu items are defined within <item> </item> tags As a minimum the item need the following options android:id - identifier of the item android:orderInCategory – the position of the item in the menu,
  • 45. higher goes first android:title – the text of the menu item 5 CQU - COIT20270 Application Development for Mobile Platforms 5 The Menu Inflater The onCreateOptionsMenu() is called when the Menu is drawn Call getMenuInflater().inflate(R.menu.menu_main, menu); and then return true; You should replace menu_main with the name of the xml file you created your menu resource in 6 CQU - COIT20270 Application Development for Mobile Platforms 6 The onOptionsItemSelected method The onCreateOptionsMenu() is called when the Menu is drawn Call getMenuInflater().inflate(R.menu.menu_main, menu); and then return true; You should replace menu_main with the name of the xml file you created your menu resource in
  • 46. 7 CQU - COIT20270 Application Development for Mobile Platforms 7 Context Menu To associate a context menu with a view you call the setOnCreateContextMenuListener() on the view The item to associate the context menu with uses the setOnCreateContextMenuListener() to listen for any tap and holds on the view You override the onCreateContextMenu() method and call your CreateMenu() method within it 8 CQU - COIT20270 Application Development for Mobile Platforms Get student to Google epistemological 8 Data Persistence Objectives, to : Save and load data with user preferences Persist data to files Create and use databases 9 CQU - COIT20270 Application Development for Mobile
  • 47. Platforms Saving and Loading User Preferences To save data objects you can Write the objects to a file Save the object to a database Use a SharedPreferences object To use a SharedPreferences object you save a name/value pair to SharedPreferences and this is then saved into an XML file for you 10 CQU - COIT20270 Application Development for Mobile Platforms Accessing Preferences in an Activity You 1st need to create a myapppreferences.xml file to use for saving your data Within this xml file you need to create key:value pairs for the data you wish to save Create an activity that extends the PreferenceActivity class and call the addPreferencesFromResource() method to load the xml file containing the preferences 11 CQU - COIT20270 Application Development for Mobile Platforms Retrieving and Modifying Preference Values To make use of preferences you use the SharedPreferences class The getSharedPreferences() method is used to get an instance of the SharedPreferences class using the name of the XML preferences file You then create a SharedPreferences.Editor() object and use a
  • 48. putString() method to change the value of a string preference To save the change to the XML file you use the commit() method 12 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the files working and discuss how they work 12 Changing the Default Name of a Preferences File Using the PreferenceManager class you can call a getPreferenceManager() method and then set the instance of this to use a new name by calling the setSharedPreferenceName() and passing in the new name 13 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 13 Persisting Data to Files To store data to files use the java.io package You can write data to the devices internal store by Writing text to a file using the FileOutputStream class and the openFileOutput() method with MODE_WORLD_READABLE (public read access), MODE_PRIVATE (private access), MODE_APPEND or MODE_WORLD_WRITEABLE (public write access) To convert a character stream to a byte stream create a
  • 49. OutputStreamWriter instance using OutputStreamWriter() and then use the write() method to write to the file. Remember to flush() and close() the file 14 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 14 …Persisting Data to Files You can read data from the devices internal store by using the FileInputStream class and the openFileInput() passing the file name as an input parameter. Then use the instance of the FileInputStream to create a new InputStreamReader() The input file is read in blocks of READ_BLOCK_SIZE bytes into a character array buffer you create. The read() method is used for this. read() returns -1 when the end of file is reached 15 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 15 Saving to External (SD card) Storage Use the getExternalStorageDirectory() method to get a File object that points to your SD card’s path To write to the SD card you then create a new directory using the previously found path using mkdirs() You can then use the previously discussed FileOutputStream() method to write objects to the file
  • 50. 16 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 16 …Saving to External (SD card) Storage To load data from the SD card use the path and filename approach used to write to the file and use a FileInputStream object instance along with an InputStream instance to read from the file In order to write to a file you need to set the WRITE_EXTERNAL_STORAGE permission in your Android.Manifest file 17 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 17 Choosing a Storage Option If you have data that can be represented using name:value pairs then use the SharedPreferences approach to store your data If your data is not in easily put into name:value pairs and is not going to be shared with other apps then use internal storage to save your data If your data is to be shared with other apps or users then use the SD card storage option
  • 51. 18 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 18 Using Static Resources You can add files to your projects res/raw folder. These files are then usable in your app Use the getResources() method to return a Resources object to get access to the file in res/raw The resource ID is used to identify the required resource. It is the name of the file in res/raw without its extension 19 CQU - COIT20270 Application Development for Mobile Platforms Creating and Using Databases Using a relational database to store tables of data is efficient as database queries can be used to retrieve the data Android uses the SQLite database system to provide access to a database, only to the app that created it The created database is stored in the /data/data/<package_name>/databases folder 20 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the files working and discuss how they work
  • 52. 20 Creating a DBAdapter Helper Class It is a good idea to create a helper class to create, open, close and use a SQLite database A database has a name, tables and columns You need to create constants to name the fields of your database The DATABASE_CREATE constant contains the SQL statements for creating the table of the database Within your DBAdapter class create a DatabaseHelper class that extends SQLiteOpenHelper 21 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 21 …Creating a DBAdapter Helper Class Override the onCreate() method to create the new database Override the onUpgrade() method for use when the database is upgraded You then define methods to use for opening, closing and adding, deleting or updating rows in the table Android uses the Cursor class to return values from queries ContentValues object is used to store name:value pairs using its put() method 22 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works
  • 53. 22 CRUD Operations on the Database As an example we will look at adding contacts to the contacts database Use the DBAdapter class to create a new instance of the DBAdapter class To retrieve contacts in the contacts table use the getAllContacts() method. This returns a Cursor object. You can use the moveToFirst() and moveToNext() methods to examine each contact in turn. The contact details are found by calling DisplayContact() on the cursor object 23 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 23 …CRUD Operations on the Database To retrieve a single contact use its ID and call the getContact() method to get the details which is returned in a Cursor object To update a contact call the updateContact() method passing the ID as the 1st parameter To delete a contact use the deleteContact() method with the contact ID as the parameter To upgrade a new database to a new one change the DATABASE_VERSION field in the DBAdapter class to a higher value than the old one. This deletes the old table, ready for the new table to be created from an existing one or otherwise 24 CQU - COIT20270 Application Development for Mobile Platforms
  • 54. Demonstrate the file working and discuss how it works 24 Pre-creating a Database Often the database is pre-created at design time and used at run- time Tools are used to create the initial database, such as that at sourceforge.net/projects/sqlitebrowser. This tool allows you to visually create the fields for the database and populate the fields with values The database is copied into the assets folder of your project. When the application is created you copy the database in the assets folder into the /data/data/<project_name>/databases folder if it does not already exist. You can then use it as before 25 CQU - COIT20270 Application Development for Mobile Platforms Demonstrate the file working and discuss how it works 25 COIT20270 Application Development for Mobile Platforms Week 6: Content Providers Dr. R. Balsys, CQU, 2018. Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016 Content Providers
  • 55. Objectives, to : share data in Android use a content provider CQU - COIT20270 Application Development for Mobile Platforms Content Providers Content providers are the recommended way of sharing data in Android application Content providers provide a consistent interface programming interface across all Android applications Content providers provide much the same services as databases – add, delete, query, edit but can be stored as databases, files or over a network Basic Android content providers include; Browser – bookmarks, history, etc. CallLog – missed calls, call details, etc. Contacts – contact details from address book MediaStore – for audio, video and images Settings – device settings and preferences CQU - COIT20270 Application Development for Mobile Platforms …Content Providers A URI is used to query a content provider. Query strings always have the form content:// <authority> / <path> / <id> where authority– name of the content provider. For user defined content providers it is the fully qualified name, eg wrox.com.provider path– specifies the content provider data path to the service provided
  • 56. id– specifies the actual record required Eg. Content://contacts/people/4 the fourth person in the people table of the devices contacts database Table 8.1 in chapter 8 of the DiMarzio text gives further examples CQU - COIT20270 Application Development for Mobile Platforms Using a Content Provider You must first specify the URI of the content provider Uri myContacts = Uri.parse(“content://contacts/people/”); Post Honeycomb devices use CursorLoader() to get a cursor instance to the data, but does not block the application thread The CursorAdapter object maps data from the source to the destination variables. You set up an array of string, String[], for the column variable and an int[] for the views You then create a new instance of a SimpleCursorAdapter class variable using the column and view values as parameters Honeycomb and later requires the addition of a FLAG_REGISTER_CONTENT_OBSERVER argument You also need to set READ_CONTACTS permission in the Android.manifest file CQU - COIT20270 Application Development for Mobile Platforms Pre-defined Querystring Parameters A number of pre-defined Query string constants are defined including: Browser.BOOKMARKS_URI CallLog.CONTENT_URI MediaStore.Images.Media.INTERNAL_CONTENT_URI MediaStore.Images.Media.EXTERNAL_CONTENT_URI Settings.CONTENT_URI
  • 57. Eg Uri contacts= ContactsContract.Contacts.CONTENT_URI; If you want to retrieve the 1st setting use Uri settings= ContentUris.withAppendedId(ContactsContract.Contacts.CONT ENT_URI, 2); CQU - COIT20270 Application Development for Mobile Platforms Printing Cursor objects Create a method that takes the Cursor variable as input Use the Cursor classes moveToFirst() and moveToNext() to iterate through the items in the Cursor object The ContactsContract.Contacts._ID field returns the ID of the contact and the ContactsContract.Contacts.DISPLAY_NAME returns the contacts name Use ContactsContract.Contacts.HAS_PHONE_NUMBER to determine if the contact has a phone number and then ContactsContract.CommonDataKinds.Phone.NUMBER to access the phone number CQU - COIT20270 Application Development for Mobile Platforms Content Providers - Projections The 3rd parameter of CursorLoader() returns the columns that are returned by the query – this parameter is known as the projection You can set up an array to contain the columns you wish to return from the data source and pass this as the projection parameter String[] projection= new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER };
  • 58. CQU - COIT20270 Application Development for Mobile Platforms Content Providers - Filtering The 4th and 5th parameters of CursorLoader() enable you to make a WHERE clause enquiry CursorLoader cL=new CursorLoader(this, contacts, projection, ContactsContract.Contacts.DISPLAY_NAME” + “ LIKE ‘Ron’ ”, null, null); You can use the next parameter to supply a list strings to use instead CursorLoader cL=new CursorLoader(this, contacts, projection, ContactsContract.Contacts.DISPLAY_NAME” + “ LIKE ? ”, new String[] {“Ron”, “Mary”}, null); CQU - COIT20270 Application Development for Mobile Platforms Content Providers - Sorting The last parameter of CursorLoader() enables you to specify an ORDER BY clause of a SQL query CursorLoader cL=new CursorLoader(this, contacts, projection, ContactsContract.Contacs.DISPLAY_NAME” + “ LIKE ? ”, new String[] {“Ron”, “Mary”}, ContactsContract.Contacts.DISPLAY_NAME” + “ ASC ”); CQU - COIT20270 Application Development for Mobile Platforms Creating Your Own Content Provider To create your own content provider you provide a class that extends the ContentProvider base class
  • 59. You need to override the following methods; getType() – to return the MIME type of the data for the URI onCreate() – called when provider created query() – receives a client request and returns a Cursor object insert() – inserts a new record in the content provide delete() – deletes records in the content provider update() – updates a record in the content provider You can store your data in the file system, a database, an XML file or through a web service CQU - COIT20270 Application Development for Mobile Platforms …Creating Your Own Content Provider You then need to define a number of strings such as the PROVIDER_NAME, CONTENT_URI, _ID, a UriMatcher instance, and a SQLiteDatabase with its associated constants The UriMatcher object is used to parse the content URI through the ContentResolver You write a SQLiteHelperDatabase class to help manage the database You then write the implementations for getType(), onCreate(), query(), insert(), delete() and update() Call notifyChange() of the ContentResolver after insert() and delete() Modify the Android.Manifest file by adding the <provider> element CQU - COIT20270 Application Development for Mobile Platforms Using Your Own Content Provider You need to create an activity to test your content provider To add to the provider create a ContentValues object and populate it with the required values for your data object
  • 60. If the ContentProvider is in the same package as your tester you can directly reference the provider fields, otherwise you need to specify the field names directly For external packages you need to refer to the content URI using a fully qualified URI You should then write methods to display the contents of you content provider and to test the update() and delete() methods CQU - COIT20270 Application Development for Mobile Platforms COIT20270 Application Development for Mobile Platforms Week 8: Networking Dr. R. Balsys, CQU, 2018. Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016 Week 8 – Networking This week we: Connect to the web using HTTP Use XML web services Use Jason web services 2 CQU - COIT20270 Application Development for Mobile Platforms Using the HTTP web services HTTP is used as the main protocol in the WWW It is used in tasks such as downloading web pages, and binary data such as images, sound and video
  • 61. To use the HTTP protocol your app must set the uses INTERNET permission in your Android manifest file You use the OpenHttpConnection() method that takes an URL string as parameter to open a connection to the specified URL By opening an InputStream object you can download bytes from the URL 3 CQU - COIT20270 Application Development for Mobile Platforms …Using the HTTP web services You must set the connection method using setRequestMethod(). Usually you use the HTTP GET verb for this When the connection is established a HTTP response code is returned. If this is HTTP_OK then you can proceed to get the data using getInputStream() 4 CQU - COIT20270 Application Development for Mobile Platforms Downloading Binary Data To download an image from a web server you use the synchronous DownloadImage() method. This returns a Bitmap object. It does this by opening a HTTP connection to the URL and uses the decodeStream() method of the BitmapFactory class to decode the InputStream instance and return it as a Bitmap Since Android 3.0 all synchronous tasks must be wrapped in the AsyncTask class to prevent them from stalling the UI You create a DownloadImageTask that extends AsyncTask<String, Void, Bitmap>
  • 62. 5 CQU - COIT20270 Application Development for Mobile Platforms …Downloading Binary Data In the DownloadImageTask class you define the methods doInBackground() and onPostExecute() In doInBackground() you call DownloadImage() to get the bitmap In onPostExecute() you display the image in your UI using a UI element You call your DownloadImageTask class by creating an instance of it in onCreate() and then calling execute() on the instance, passing a URL as the parameter 6 CQU - COIT20270 Application Development for Mobile Platforms …Downloading Binary Data To read multiple images you modify the doInBackground() method to use a for loop to loop through each of the URLs. As each image is completed you call publishProgress() to give feedback An extra onProgressUpdate() method is defined in the DownloadImageTask class to display the downloaded images In onCreate() you pass multiple URLs as the parameters of the execute() method NOTE: On the emulator localhost refers to the emulator itself. If getting images from your PC use your PCs IP address instead of localhost or the files will not be found 7 CQU - COIT20270 Application Development for Mobile Platforms
  • 63. Downloading Text In some circumstances you may wish to GET plain text files. The text file is stored as a String on the device To achieve this write a DownLoadText(URL) method that returns the text file as a single String You open a Http connection to an InputStream object. Then use an InputStreamReader instance to a new InputStreamReader() instantiated with your InputStream object You read the incoming stream of bytes into character buffers and append the incoming String copy of the buffer contents to the final returned String You create a subclass of AsyncTask to call DownLoadText(URL) asynchronously as before 8 CQU - COIT20270 Application Development for Mobile Platforms Accessing Web Services using GET Many Web services respond to a GET query with an XML file We need to be able to connect to the web service and then parse the contents of the XML file For example consider a web service that returns the dictionary definition of the word (eg http://services.aonware.com/DictService/DictService.asmx?op= word ) Here you need to establish the connection to the web service and then parse the XML returned 9 CQU - COIT20270 Application Development for Mobile Platforms …Accessing Web Services using GET
  • 64. Here we create a WordDefinition(String) method that returns the XML file in a local String object. We wrap this in a subclass of AsyncTask and call WordDefinition (String) asynchronously Use OpenHttpConnection() and pass the request string as the URL, remembering to use the required word at the end of the string You create a local instance of a Document object and use the newInstance() method of the DocumentBuilderFactory class to create a DocumentBuilderFactory instance 10 CQU - COIT20270 Application Development for Mobile Platforms …Accessing Web Services using GET You also need a DocumentBuilder object defined and then you can use your DocumentBuilderFactory instance to try and get a valid DocumentBuilder object. You call the parse() method get a Document object The elements of the word definition are then found within the <definition> tags in the Document object model (DOM) 11 CQU - COIT20270 Application Development for Mobile Platforms Consuming Jason Services XML has a number of disadvantages: Documents sizes get big as the complexity goes up and so costs rise Parsing the XML to extract the content of the message is CPU intensive, requires the complete DOM to be stored locally as a tree structure so is memory intensive A more efficient representation scheme is to use JavaScript object notation (JSON) to encode the information
  • 65. 12 CQU - COIT20270 Application Development for Mobile Platforms JASON JavaScript Object Notation (JSON) is a data exchange format for defining data structures JSON is light-weight and easy to read and write JASON objects are represented as “key”:”value” pairs enclosed in {}’s, eg. {"a":"I", "b": ["d", "e", "f"], "c":{"a": 1000, "b":["fred"]} } 13 CQU - COIT20270 Application Development for Mobile Platforms Consuming JSON Services To consume JSON services you create a readJSONFeed() method This method connects to the specified URL and then reads the response from the web service as a String You call the readJSONFeed() method asynchronously using the AsyncTask class readJSONFeed() in called in the AsyncTask’s doInBackground() method and the JSON String you fetch is passed into the onPostExecute() method of the AsyncTask 14 CQU - COIT20270 Application Development for Mobile Platforms Go to the API and read through the entries
  • 66. 14 …Consuming JSON Services To obtain the list of objects in the JSON String you pass the JSON received into a JSONArray() constructor to get a local JSONArray object representing the JSON data You can then use the length() method to get the length of the JSON array and get a JSONObject from the JSONArray using the getJSONObject() method To get the key:value pair from a JSON object you use getString(), getInt(), getLong() or get Boolean() 15 CQU - COIT20270 Application Development for Mobile Platforms Go to the API and read through the entries 15 COIT20270 Application Development for Mobile Platforms Week 9: Developing Android Services and App testing Dr. R. Balsys, CQU, 2018. Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016 and https://www.tutorialspoint.com/mobile_testing/mobile_testing_q uick_guide.htm Week 9 – Developing Services Objectives, to:
  • 67. To create an Android service that runs in the background Perform long running tasks in threads Perform repeated tasks in a service Understand how activities and services communicate Understand threading in Android 2 CQU - COIT20270 Application Development for Mobile Platforms Android Services Services are tasks that run in the background without the need for a UI, e.g playing background music or repeatedly polling for the devices current location To create a service you extend the Service base class and override: onBind(): binds the activity to the service onStart(): used to do things when the service first starts onDestroy(): called when the service terminates and is used to clean up resources used by the service 3 CQU - COIT20270 Application Development for Mobile Platforms Go to the API and read through the entries 3 …Android Services Services must be declared using the service tag, or an action tag in your intent-filter section for services that are available to other applications, in the Android manifest file You start the service using the startServices() method You stop a service by calling the stopService() method 4
  • 68. CQU - COIT20270 Application Development for Mobile Platforms Go to the API and read through the entries 4 Performing Long Running Tasks Long running tasks will stall your UI making your activity unresponsive For this reason long running tasks are put into a separate thread so the main thread can keep running You implement an inner class that extends the asynchronous AsyncTask class without manually creating threads and handlers 5 CQU - COIT20270 Application Development for Mobile Platforms Go to the API and read through the entries 5 The AsyncTask Class The AsyncTask class has three generic types URL, Integer and Long These type of parameters are passed to the doInBackground(), onProgressUpdate() and onPostExecute() methods of the AsyncTask class doInBackground() accepts an array of String’s corresponding to URL’s as its parameter. In this method you implement the long running task. To report progress you call publishProgress() method passing the Integer % complete onProgressUpdate() connects to UI’s elements to show tasks
  • 69. percentage complete onPostExecute() takes the Long value returned by doInBackground() when it completes as its parameter and is used to take action when this happens Call stopSelf() in onPostExecute() to terminate the Service or it keeps running 6 CQU - COIT20270 Application Development for Mobile Platforms new Media is correct capitalisation for the constructor 6 Doing Repeated Tasks in a Service You may want to use the Timer class to arrange for a service to be run at set time intervals The TimerTask class implements a Runnable interface and runs on its own thread. Hence it does not have to extend the AsyncTask class to be run in the background 7 CQU - COIT20270 Application Development for Mobile Platforms 7 …Doing Repeated Tasks in a Service To repeat the service in the class create a method in your Service and in it use a Timer object and call its scheduleAtFixedRate() method passing in a new TimerTask() that implements a run() method as scheduleAtFixedRate()’s 1st parameter, the delay before the 1st call of the run() method as
  • 70. the 2nd parameter and the delay between successive calls in milli-seconds as the 3rd parameter Call your new method directly from the onStartCommand() method of your Service 8 CQU - COIT20270 Application Development for Mobile Platforms 8 Asynchronous Tasks on Separate Threads Using IntentService The IntentService class makes it easy to create an asynchronous task that terminates when completed IntentService is based on the Service class and handles asynchronous requests on demand It is started like a normal service, executes on a separate worker thread and terminates itself when completed 9 CQU - COIT20270 Application Development for Mobile Platforms 9 …Asynchronous Tasks on Separate Threads Using IntentService To use IntentService class you define a new class that extends IntentService You need to implement a constructor that calls the superclass passing in a string to name the service You also need to override the onHandleIntent() method to specify the action the service is to take when executing on the
  • 71. worker thread When onHandleIntent() is finished the thread is terminated and then service is automatically stopped 10 CQU - COIT20270 Application Development for Mobile Platforms 10 Week 9 – Mobile App Testing This week we: Understand the importance of testing the the apps we develop for mobile devices Develop a methodology for testing mobile devices Understand how to choose which mobile devices we should test Discuss strategies for testing on a range of devices (including emulators) Look at developing a mobile device test plan 11 CQU - COIT20270 Application Development for Mobile Platforms The Importance of App testing There is a lot of competition for application and services on mobile devices Testing ensures that your device functions as intended If your app fails at some task, is poorly designed or is unresponsive your customers will move on to something else very quickly The goal of testing is to determine the quality of the software – does it work, does it function as intended and does it meet the
  • 72. users needs Failure means your customers will desert you for other suppliers 12 CQU - COIT20270 Application Development for Mobile Platforms Mobile Testing Methodology Comprehensive testing is complicated and expensive In Mobile apps use is often made of the WWW (even though it does not have too) so account must be taken of this Testing must not just be restricted to the mobile device but any services or peripherals the app uses 13 CQU - COIT20270 Application Development for Mobile Platforms Note: The reading addresses testing mobile web sites rather than mobile app testing. However, a lot of similarity occurs between the two 13 …Mobile Testing Methodology According to Wikipedia mobile application testing includes Functional testing Laboratory testing – of complete wireless network Performance testing – undertaken under different conditions Memory leakage – test apps memory management Interrupt testing – how it handles interrupts such as battery removal, notifications, incoming/outgoing calls, etc.. Usability testing Installation testing in actual practice Any certification testing required by customers
  • 73. 14 CQU - COIT20270 Application Development for Mobile Platforms Note: The reading addresses testing mobile web sites rather than mobile app testing. However, a lot of similarity occurs between the two 14 Choosing Devices to Test Comprehensive testing targets multiple device models, operating systems, mobile networks and possible browsers It generally is not possible to test on every mobile device so a reasonable subset must be chosen The process to follow includes; List all target devices Organise devices by operating system and version Organise devices by modality and input method Choose the strongest and weakest from the list for testing 15 CQU - COIT20270 Application Development for Mobile Platforms Note: The reading addresses testing mobile web sites rather than mobile app testing. However, a lot of similarity occurs between the two 15 Strategies for Testing on Devices The greatest issue is to acquire the range of devices needed for testing This can be done by
  • 74. Purchasing the devices outright Joining industry developer programs Use the services of a commercial provider to test Use device emulators for testing 16 CQU - COIT20270 Application Development for Mobile Platforms Note: The reading addresses testing mobile web sites rather than mobile app testing. However, a lot of similarity occurs between the two 16 Developer Programs and Emulators All the major manufactures of mobile devices have developer programs that you can join for a fee that may provide discounted device purchases, you to rent or borrow devices and/or access to virtual devices Emulators are a relatively inexpensive alternate to real devices, however these are not the real devices and problems or errors can slip through the testing process In particular gestures and touches do not emulate well 17 CQU - COIT20270 Application Development for Mobile Platforms
  • 75. Note: The reading addresses testing mobile web sites rather than mobile app testing. However, a lot of similarity occurs between the two 17 Develop a Mobile Test Plan Start by writing a summary to describe the purpose of the app, its use cases and how you plan to test the device Review the list of devices, OS versions etc. you plan to test Decide whether testing uses actual devices, emulators or both. If using actual devices decide how the devices are to be acquired Write scripts to detail the tests to be undertaken on the devices and carry out the tests 18 CQU - COIT20270 Application Development for Mobile Platforms Note: The reading addresses testing mobile web sites rather than mobile app testing. However, a lot of similarity occurs between the two 18 COIT20270 Application Development for Mobile Platforms Week 10: App Stores and Marketing Dr. R. Balsys, CQU, 2018. Source: Beginning Mobile Application Development in the
  • 76. Cloud, R. Rodger, 2012, ch. 13 pp. 435-441. Week 10 – App Stores & Selling Your App This week we: Create icons & splash screens for Apps Prepare screenshots and App metadata Understand AppStore terms and conditions Determine how to develop a marketing plan Understand freelance work Understand how to use apps for business promotion Use both standard and guerilla marketing tactics Learn about building communities around our apps 2 CQU - COIT20270 Application Development for Mobile Platforms Icons and Splash screens Icons are visually associated with your app and need to be well designed and aesthetically pleasing They should be designed by a graphics designer and a number of different sized .png images are required You full app also requires a “splash” screen Screenshots of the main screens of your app are required for submission to Apple’s App Store and the Android marketplace On Android you can get a screenshot by holding the Back key and also holding the Home key down for a few seconds or by taking a screenshot from the emulator 3 CQU - COIT20270 Application Development for Mobile Platforms App Metadata When submitting an App to a store the following information is
  • 77. required A short textual description of the app The category to which your app belongs Keywords relevant to search results for the app Supporting website address for the app Any promotional graphics or video A change log for the app A content rating The market geographical regions 4 CQU - COIT20270 Application Development for Mobile Platforms Working With the App Store App must be submitted and accepted before they are available Apps need to be digitally signed The general business model is that the store receives 30% of either the sales price or the subscription fee, to be paid every 30 days In-app advertising revenue appears to be exempt from the terms You need to read the terms and conditions that apply to the use of both the Android Marketplace and Apple’s App Store 5 CQU - COIT20270 Application Development for Mobile Platforms Determining a Marketing Strategy A number of questions need to be answered to define a marketing strategy. Specifics include: Demographics, what are the sex, ages and incomes of target audience Needs, what user need does the app fill? Cost of promotion, how much will advertising cost relative to the market size?
  • 78. How will the app be used? You need to test and verify that your answers are correct 6 CQU - COIT20270 Application Development for Mobile Platforms Building Apps for Other Most likely you will be building apps for your employer or on a contract basis for someone. You should build for success Explain to clients the importance of usability, meeting app store guidelines, common interface conventions, the economics of cloud hosting, and how to launch and market the app Make sure you have a documented contract for work, have received a down-payment before starting and invoice your time and costs as they occur Offer fixed rate or standard time and materials day rates. The fixed price should be about 50% extra to cover time blow-outs in development Offer a discount for early payment 7 CQU - COIT20270 Application Development for Mobile Platforms Promoting Your Business A number of strategies can be used to promote your business Subscription Based Services. Here the app is distributed for free but a monthly subscription is charged for services. The key is that the service must be of value to the customer or they will not pay Offering free versions of the app. These all limit the functionality of the app. The idea is the user can get a feel for the app. The fully featured app is then purchased If your business already has a commercial presence then the app can be promoted through those channels
  • 79. Selling in-app Ads. If enough people use your app then selling advertising space in the app can be a useful revenue stream Premium services can be offered at a higher rate In-app purchases. In this model the app is free or almost so, revenue is gained by selling items, eg games offering magical items for real $’s Cross application apps are developed once but deployed across multiple devices thus increasing market base and potential revenue 8 CQU - COIT20270 Application Development for Mobile Platforms Selling Apps You need to be clear on why you are developing apps and whether you are building reputation or trying to make money Coding plays a relatively small part in the time involved in selling apps. Most of your time will be spent marketing the app You need to set goals such as What apps for what audience How much income per month are you targeting Only build what can be done. Plan for apps that take about a month to develop Consider how you will pay the bills before your income starts turning up Set timelines for the progress in 1st 3 months and stick to it Use a spreadsheet to model all your expenses and expected income 9 CQU - COIT20270 Application Development for Mobile Platforms Embracing Marketing
  • 80. You need to understand marketing. If you want to make money then your target demographic must be able to buy the app You need to understand where your market goes to find information and make sure your product information can be found there Each app must be continually updated and marketed You must either develop 1 or 2 high value apps or, more likely, develop a large number of less costly apps 10 CQU - COIT20270 Application Development for Mobile Platforms Marketing Tactics There are a large number of apps out there, getting noticed is hard You need to keep track of every $ spent on an app and your time spent on an app. Use a spreadsheet for this and convert your time into dollars on a contracting basis. Monitor this on a weekly basis and if an app does not pay then consider spending your time elsewhere Only advertise in arenas where you know you will get customers from Use real people to help you user test your ideas. From this develop your marketing ideas Plan your marketing campaign to last months, using advertising, blogs and other means for this 11 CQU - COIT20270 Application Development for Mobile Platforms
  • 81. Standard Tactics Create a website to go with your app. It allows you to market and service your customers Have a forum on the website and continuously mine the forum for useful information Use social forums to spread the message about your app Create a mailing list forum for you app and use this to spread marketing information Develop promotional material for your app and use it. Use different promotional material and track the effectiveness of it Give your app to well known bloggers in the hope they will write about it You can use traditional media for advertising as well Submit your apps to mobile app competitions Provide a free lite version of your app Price your app competitively 12 CQU - COIT20270 Application Development for Mobile Platforms Expensive Tactics Advertise your apps on on app directory site where the ad will be seen You can target high readership content sites and or advertise within other popular apps Create a sustained media campaign targeting social media and major content sites Use an advertising agency to do the promotion for you You can also use offline advertising such as radio, TV and newspapers to advertise 13 CQU - COIT20270 Application Development for Mobile
  • 82. Platforms Guerilla Tactics A young individual is unlikely to have much money to put into advertising, so use non-traditional ways of getting your message out Build a community around your app. Forums where you actively participate with your users is one way to do this You can start a forum with your test users and encourage them to bring their friends along You can offer in-app rewards to people for helping marketing your product You can offer rewards to bug-hunters to find bugs in your code Have a social media sharing page in your app users can use to connect to social sites 14 CQU - COIT20270 Application Development for Mobile Platforms …Guerilla Tactics Direct potential customers to the app websites where screenshots, videos etc., can help them make the buy decision Ignore piracy – pop up a “please buy” message occasionally to encourage purchase Try to develop a high value content blog for your app Provide links to your apps and app website in your email signature 15 CQU - COIT20270 Application Development for Mobile Platforms
  • 83. Assessment item 1— Portfolio Due date: 11:50 pm AEST, Friday of week 12 Portfolio Weighting: 20% 1 Length: Less than 50 MB Objectives This assessment item relates to the course learning outcomes numbers 2, 3 and 5 as stated in the online course profile. Details You are to submit a weekly portfolio submission, using Mahara, for weeks 2 to 11 inclusive. To access Mahara, click the "CQU Portfolio" link in the Network Services block on the left- hand side of the Moodle site. The weekly portfolios will describe your understanding of the topic for the week, with relevant references and resources providing evidence of your understanding. You are to conduct a search of the internet on the topic for the week. You should review the items you find and select a minimum of 5 items and link them to your portfolio. You are not to upload files from the internet, as you do not own copyright, and if you do, this will be plagiarism. You are to use links to your items only. You may include items from YouTube, clips from lectures and/or tutorials, and your own work that you produce in the tutorials. Your portfolio should capture rich ideas, resources and innovative practice around mobile app
  • 84. development within the frame of the weekly topics. You are to write a brief discussion for each week as to why you chose the items you did, and why you thought the items chosen are appropriate. Harvard referencing format and citations are to be used to substantiate your discussion. Assessment Criteria Each portfolio submission will be assessed against the following criteria: Criteria Marks/week Summary of weekly topic 0.5 Resource descriptions 1 Number and justification/quality of resources 0.5 Penalties Total 2