SlideShare a Scribd company logo
1 of 157
Android
Applications
Development
Getting started on the Android
Platform 
March 12 – 14, 2014
Prepared By
Michael Angelo M. Rivera
Deuphil B. Kaufmann
Agenda
 What’s the Android platform ?
 Version History.
 Android and beyond (Future)
 All about the Android Architecture
 Tools and SDK overview.
 Hello Android Walkthrough
 Android User Interface.
Agenda
 Activities & Intents
 Working with Services
 BroadcastReceiver
 SQLite and ContentProvider
 SharedPreferences
 Connecting to the Internet
 The Android Manifest
Android
 OS based on the Linux kernel & designed
primarily for touchscreen mobile devices such
as smartphones & tablet computers.
 Initially developed by Android, Inc., which
Google backed financially & later bought in
2005, It was unveiled in 2007 along with the
founding of the Open Handset Alliance—a
consortium of hardware, software, & telecom
companies devoted to advancing open
standards for mobile devices.
Android
 provides a rich application framework
that allows you to build innovative apps
and games for mobile devices in a Java
language environment.
 powers hundreds of millions of mobile
devices in more than 190 countries
around the world.
Android
 The first publicly available smartphone
running Android, the HTC Dream (G1),
was released on October 22, 2008
Android
 As of September 2013, one billion Android
devices have been activated
History – Android Versions
History – Android Versions
Android 1.5, Cupcake
 Introduced: April 30, 2009
 Key features in this version of Android:
Integration of home screen widgets,
support for folders on home screen, stereo
Bluetooth support, copy/paste in web
browser, video recording and playback.
 Notable devices of the day: HTC Hero, T-
Mobile G1, T-Mobile Cliq, Samsung
Moment, LG Eve, Motorola Backflip
History – Android Versions
Android 1.6, Donut
 Introduced: September 15, 2009
 Key features in this version of Android:
Quick search box, updated interface for
camera, camcorder, and gallery, updated
Google Play (Android Market), battery
usage indicator, text-to-speech engine,
 Notable devices of the day: LG Optimus,
Motorola Devour, Samsung Behold II,
Samsung Galaxy, Sony Ericsson Xperia X10,
Garminfone.
History – Android Versions
Android 2.0 – 2.1 Eclair
 Introduced: October 26, 2009
 Key features in this version of Android:
Google Maps Navigator (beta), updated
browser, support for multiple accounts,
improved keyboard, SMS search, Exchange
support.
 Notable devices of the day: Motorola
Droid, Motorola Charm, Motorola Flipout,
Samsung Galaxy S, Acer Liquid E, HTC
Desire.
History – Android Versions
Android 2.2 – 2.3 Froyo
 Introduced: May 20, 2010
 Key features in this version of Android:
Support for Adobe Flash, portable hotspots,
multiple keyboard languages, speed and
performance improvements, enhanced
Microsoft Exchange support.
 Notable devices of the day: Nexus One,
HTC EVO, Droid Incredible, Droid X,
Samsung Droid Charge, Sidekick 4G.
History – Android Versions
Android 2.3 – 2.3.7 Gingerbread
 Introduced: December 6, 2010
 Key features in this version of Android: UI
refinements, NFC support, native support for
SIP VOIP, faster/more intuitive text input,
enhanced copy and paste.
 Notable devices of the day: Nexus S, HTC
Sensation, HTC EVO 3D, Motorola Droid
Razr, Samsung Galaxy S II, Sony Xperia Play
History – Android Versions
Android 3.0 – 3.2 Honeycomb
 Introduced: February 22, 2011
 Key features in this version of Android:
Revamped (holographic) UI designed
specifically for tablets, action bar,
improved multi-tasking, updated standard
Android apps, better copy/paste,
redesigned keyboard.
 Notable devices of the day: Motorola
Xoom, Eee Pad Transformer, Samsung
Galaxy Tab.
History – Android Versions
Android 4.0 Ice Cream Sandwich
 Introduced: October 19, 2011
 Key features in this version of Android:
improved multi-tasking, face unlock,
resizeable widgets, Android beam,
enhanced email options, improved text
and voice input, soft buttons can replace
hard keys.
 Notable devices of the day: Galaxy Nexus,
HTC One X, LG Optimus G, Samsung Galaxy
Note 10.1, Motorola Droid Razr M, Sony
Xperia T.
History – Android Versions
 Android 4.1 – 4.3 Jelly Bean
 Introduced: July 9, 2012
 Key features in this version of Android: larger,
rich, and actionable notifications, Google Now,
offline voice dictation, streamlined UI,
performance improvements “Project Butter”,
smart widget placement, multi-user profiles for
tablets (4.2), lock screen widgets (4.2),
daydream (4.2), OpenGL ES 3.0 (4.3), Bluetooth
Smart Ready (4.3), restricted user profiles for
tablets (4.3).
 Notable devices of the day: Samsung Galaxy
S3, Samsung Galaxy S4, Samsung Galaxy Note
3, Motorola Moto X, LG G2, Sony Xperia Z, HTC
One, Motorola Droid Razr Ultra.
Android and beyond
Android and beyond
Android 4.4 – 4.4.2, KitKat
 Introduced: October 23, 2013
 Key features in this version of Android: Host
Card Emulation,Printing framework,Storage
access framework,Low-power sensors,SMS
provider,Full-screen Immersive
mode,Transitions framework,Chromium
WebView,Screen recording,RenderScript
NDK,Bluetooth HOGP and MAP,IR
Blasters,Closed captioning settings,RTL
features,Security enhancements ,Tools for
analyzing memory use.
Android and beyond
Android and beyond
Android and beyond
Host Card Emulation (HCE)
 introduces new platform support for
secure NFC-based transactions
through Host Card Emulation (HCE),
for payments, loyalty programs, card
access, transit passes, and other
custom services. With HCE, any app
on an Android device can emulate
an NFC smart card, letting users tap
to initiate transactions with an app of
their choice
Android and beyond
IR Blasters
 you can build apps that let users
remotely control nearby TVs, tuners,
switches, and other electronic
devices. The API lets your app check
whether the phone or tablet has an
infrared emitter, query it's carrier
frequencies, and then send infrared
signals.
Android and beyond
Wearables
Android and beyond
The Open Automotive Alliance-
 is a global alliance of technology and
auto industry leaders committed to
bringing the Android platform to cars
starting in 2014.
Android Architecture
Android Architecture
 Linux Kernel
 Relies on Linux version 2.6 for core system
services such as security, memory
management, process management, network
stack and driver model.
 The kernel also acts as an abstraction layer
between the hardware and the rest of the
software stack.
Android Architecture
 Dalvik Virtual Machine
 It is a type of JVM used in android devices to
run apps and is optimized for low processing
power and low memory environments. Unlike
the JVM, the DVM doesn’t run .class files,
instead it runs .dex files. .dex files are built
from .class file at the time of compilation and
provides higher efficiency in low resource
environments. The Dalvik VM allows multiple
instance of Virtual machine to be created
simultaneously providing security, isolation,
memory management and threading support.
It is developed by Dan Bornstein of Google.
Android Architecture
 Core Java Libraries
 These are different from Java SE and Java ME
libraries. However these libraries provides most
of the functionalities defined in the Java SE
libraries.
Android Architecture
 A bit more explanation
 Java source code is still compiled into .class
files. But after .class files are generated, the
“dx” tool is used to convert the .class files into
a .dex, or Dalvik Executable, file. Whereas a
.class file contains only one class, a .dex file
contains multiple classes. It is the .dex file that
is executed on the Dalvik VM.
Android Architecture
 Libraries
 Android’s native libraries. It is this layer that
enables the device to handle different types
of data. These libraries are written in c or c++
language and are specific for a particular
hardware.
Android Architecture
 Application Framework
 These are the blocks that our applications
directly interacts with. These programs
manage the basic functions of phone like
resource, activity, &voice call management
etc. As a developer, you just consider that
these are some basic tools with which we are
building our applications. Written in Java.
Android Architecture
 Applications
 the top layer in the Android architecture and this is
where our applications are going to fit. Several
standard applications comes pre-installed with every
device, such as: SMS client app, Dialer, Web browser &
Contact manager.
 As a developer we are able to write an app which
replace any existing system app. That is, you are not
limited in accessing any particular feature. You are
practically limitless and can whatever you want to do
with the android (as long as the users of your app
permits it). Thus Android is opening endless
opportunities to the developer
Tools and SDK
Tools and SDK Overview
 Software Requirements
 Java Development Kit (JDK), at least JDK 6
 http://goo.gl/kCLldE
 Eclipse IDE, at least 3.6.2 (Helios)
 32-bit - http://goo.gl/RD3wUh
 64-bit - http://goo.gl/11uQDQ
 ADT Eclipse plug-in
 Update Site -
https://dl-ssl.google.com/android/eclipse/
 Offline - http://goo.gl/BsyGQ1
 Android SDK
 http://goo.gl/3b0oNG
Tools and SDK Overview
 Setting up
 Install JDK
 Install Eclipse
 Install ADT (via Update Site or offline package)
 Extract the Android SDK to desired install location
 Note: Make sure you have the necessary access
rights to the install location
 Set Android SDK path in Eclipse under Window >
Preferences > Android > SDK Location, and select
OK
 Optional: Add to path to environment, ex.
ANDROID_HOME
Tools and SDK Overview
 Android SDK
 AVD Manager – For managing Emulators
 SDK Manager – For managing Android
Runtimes/Libraries
 tools/
 DDMS (ddms.bat) – For monitoring devices for
debugging
 9-Patch Tool (draw9patch.bat)
 LINT (lint.bat)
 Hierarchy Viewer (hierarchyview.bat)
 platform-tools
 Android Device Bridge (adb.exe)
 Logcat (adb logcat) – For getting system logs
Tools and SDK Overview
 IDEs
 Eclipse
 Android ADT Bundle (Eclipse-based)
 IntelliJ
 AndroidStudio
 Build/CI Tools
 Ant
 Maven
 Gradle
 Jenkins/Hudson
 TravisCI
 Testing
 Android Instruments (with JUnit)
 Robolectric
 Robotium
Hello Android Walkthrough
Android UI and Resources
Densities and Sizes (*cough* fragmentation)
Sizes
 Actual physical size, measured as the
screen's diagonal
 There are four generalized sizes: small,
normal, large, xlarge
Densities
 The quantity of pixels within a physical
area of the screen
 Core densities: low (ldpi), medium (mdpi),
high (hdpi), extra high (xhdpi) (, and
xxhdpi)
Densities
BAD!
GOOD!
Android Metrics
 Density-independent Pixels (dip/dp)
 Screen density independent metric equivalent to 160 dpi
 dp = px / (dpi / 160)
 Used for View and ViewGroups’ dimensions
 Scale-indepedent Pixels (sp)
 Similar to dp, but dependent on user font size preferences
 Used for text size
 Fixed System Attributes
 WRAP_CONTENT
 FILL_PARENT (deprecated and renamed MATCH_PARENT
in API Level 8 and higher)
 Pixels (px), Points (pt), (Millimeters) mm, (Inches) in
 Don’t you use them even if your life depends on it
Building Options
 Programmatically (Runtime; Swing-like)
 Using XML Layouts (Compiled; Recommended way)
Views
 The basic building block for UI components
 Occupies a rectangular area on the screen and is
responsible for drawing and event handling
 Get a reference via findViewById(resourceId:int)
 Key Views
 TextView
 EditText
 Button
 ImageButton
 ImageView
 RadioButton
 CheckBox
 Spinner
 ProgressBar
 ListView
Views
TextView
 Displays text to the user
 Key Methods
 set-/getText
 setTextStyle
 setTextSize
 setTextColor
Views
EditText
 Inherits from TextView
 On top of TextView, it
allows it to be editable
 Key Methods
 Same as TextView
Views
Button
 Represents a push-
button
 Key Methods/Events
 set-/getText
 setTextSize
 setTextStyle
 setEnabled
 View.onClickListener
Views
ImageButton
 Same as button, but
focused on an image
rather on texts
 Not a subclass of
Button
 Key Methods/Events
 setImageResource
 setImageDrawable
 setEnabled
 View.OnClickListener
Views
ImageView
 Container for images
 No GIFs 
 Key Methods/Events
 setImageResource
 setImageDrawable
Views
CheckBox
 Represents a 2-state
button, as checked
and unchecked only
 A subclass of
CompoundButton
 Key Methods/Events
 isChecked
 setChecked
 toggle
 View.OnClickListener
Views
RadioButton
 Represents a 2-state
button, as selected
and unselected only
 A subclass of
CompoundButton
 For mutual exclusive
selection, must be
wrapped around a
RadioGroup
 Key Methods/Events
 Same as CheckBox
Views
ProgressBar
 Presents a visual
indicator of progress in
some operation
 Progress can be set
incrementally or be set
a indeterminate
 Key Methods/Events
 setProgress
 setMax
 setIndeterminate
Views
Spinner
 Represents a collapsed
dropdown menu of
selection
 Populate data with an
Adapter
 Key Methods/Events
 AdapterView.OnItemS
elected
 setAdapter
Views
ListView
 Widget for displaying
lists
 Populate data with an
Adapter
 Key Methods/Events
 AdapterView.OnItemC
lick
 AdapterView.OnItemL
ongClick
 setAdapter
Adapters
 Bridges the AdapterView (ListView, Spinners etc.)to an
underlying data
 In charge of creating and managing list item Views
 Key/Common Adapter Classes
 ArrayAdapter
 BaseAdapter
 CursorAdapter
 SimpleCursorAdapter
Adapters - ArrayAdapter
 A concrete implementation of BaseAdapter backed
by an array of objects
 Usage Options
 Create an instance directly from an Array-resource via a
static method
 Create an instance with custom Objects via its
constructors
Adapters - BaseAdapter
 Base class for most Adapter implementations
 A good practice is to extend this class rather than
relying on ArrayAdapter
 This allows your code to be maintained easier as it grows
and requirements changes
 The implementer doesn’t have to worry how its made as
its encapsulated away
 Used with the infamous workaround ViewHolder-
pattern for optimizing View creations
 You may also create a custom View instead of a
ViewHolder
ViewGroups
 A special View that serves as an invisible container to
other Views/ViewGroups
 Base class for all layouts
 Includes an implementation of
ViewGroup.LayoutParams, which defines the
attributes that affects containing children Views
 Key ViewGroups
 LinearLayout
 RelativeLayout
 FrameLayout
 ScrollLayout
ViewGroup
LinearLayout
 Is a ViewGroup that aligns all its children Views into a
single direction, either vertically or horizontally
 Options are LinearLayout.HORIZONTAL and
LinearLayout.VERTICAL, default is horizontal
 setOrientation-method (programmatically)
 android:orientation-attribute (xml)
 Supports assigning of “weights” or “importance” to its
children
 setWeigtSum (programmatically); This sets the total
“weight” that can be distributed
 android:weightSum-attribute (xml)
 android:layout_weight-attribute (xml); This sets the
“weight” of the child View in relation to its parent
ViewGroup
RelativeLayout
 Is a ViewGroup that displays its child views in relative
positions
 Can position Views, relative to its parent (the
RelativeLayout) or to its neighbouring Views
 Reference to other Views is via an “assumed”
resource ID
 Sample Attributes
 android:layout_below=“@+id/someViewAbove”
 android:layout_centerInParent=“true”
 android:layout_alignParentBottom=“true”
ViewGroup
FrameLayout
 Is a ViewGroup that displays single Views on a screen
 Child positions can be changed with gravity
 Child views are drawn in a stack, last items are drawn
on top (think z-index)
 The size of the FrameLayout is based on the largest
child View
ViewGroup
ScrollView
 Is a ViewGroup that wraps its content in a scrollable
container
 Only 1 child View per ScrollView
 Is a subclass of FrameLayout
 Never use a ListView with a ScrollView
 Scroll-events will collide
 The ListView will create a view for every item, defeating
the purpose and will cause performance degradation
 It’s just plain wrong!
OptionsMenu
 Represents a menu of common actions on a screen
(ex. Help, Settings, etc.)
 Pre-Honeycomb (Android 3.0) accessible via
hardware menu button
 Honeycomb to present will present the menu in the
ActionBar
 Menu items are defined under the “menu” sub-
resource in XML (recommended)
 Called “Actions” on Honeycomb and above
ContextMenu
 Represents a menu that is contextually created,
usually on a ListView (ex. Delete, Share, etc.)
 Two implementation alternatives
 Floating ContextMenu
 ActionMode*
 Same with OptionsMenu, must be defined in the
“menu” sub-resource in XML
 Usually triggered via a long item click in a ListView (ex.
Long-Hold-To-Delete)
Toasts
 Provides a small and simple popup to feedback
about an operation
 Provides only 2 popup durations
 TOAST_SHORT – about 3 seconds
 TOAST_LONG – about 5 seconds
Dialogs
 A small window that prompts the user to make a
decision or enter additional information
 Does not fill the screen and is normally used for modal
events that require users to take an action before
they can proceed
 Cannot exist without a parent Window/Activity
 Must ensure to dismiss/de-reference to avoid leaks
 Key Classes
 AlertDialog
 AlertDialog.Builder
 ProgressDialog (avoid!)
 TimePickerDialog
 DatePickerDialog
AlertDialogs(.Builder)
 A dialog that can show a title, up to three buttons, a
list of selectable items, or a custom layout
 Provides 3 button options, a positive, a negative, and
a neutral one
 Creation is through AlertDialog.Builder
Date-/TimePickerDialog
 Provides controls for selecting each part of the time
(hour, minute, AM/PM) or date (month, day, year)
 Helps ensure that your users can pick a time or date
that is valid, formatted correctly, and adjusted to the
user's locale
 Creation is through a constructor
Resources
 Are external application artifacts and configurations
of an Android App
 Provides a system to adjust and align with different
device configuration, such as localizations, strings,
images, UIs, and animations
 There are two basic scenarios
 A developer will specify default resources that will be
used by the platform regardless of device configuration
 Example: An animation resource that is common to all device
configuration
 Or, a developer will specify multiple resources depending
on a target set of device configurations
 Example: String resources that are for both English and Spanish
users or layout resources that has one for portrait and another
one for landscape
Resources
 Resources reside under the “/res”-folder of your
project directory
 Every resource will have it’s own ID under its
namespace (Ex. R.string.hello_worldThe R.java class
contains all the generated IDs and only the SDK is
able to generate
 Usage Examples
 In XML
@<package name>:<resource type>/<resource name/id>
Ex. android:textColor=“@android:color/transparent”
 Programmatically (Runtime)
<package name>.R.<resource type>.<resource name>
Ex. editText.setText(R.string.hello_world)
Resources
 Key Resource Types
 Animation (tweens or frame animations)
 Drawable (images PNG (and/or JPG))
 Colors (HEX colors)
 Layout or UIs (your XML UI layouts)
 Menus (your OptionsMenu or ContextMenu resources)
 String (external texts and/or text localizations) Arrays
(external arrays, such as Email Types) Arrays (text arrays,
such as Email Types)
 Dimensions (pixels, points, inches, millimetres)
 Other Resource Types
 Style (UI and/or component themes)
 String Plurals (texts for defining plurality, such as “Elf” and
“Elves”)
 Color State Lists, Booleans, Integers, IDs, TypedArray
Resources
 Qualifiers
 Device Density (Ex. hdpi, xhdpi, mdpi)
 Device Size (Ex. normal, large)
 Country Code/MCC (Ex. mcc630)
 Network Code/MNC (Ex. Mnc610)
 Language (Ex. En, Es)
 Region (Ex. rUS, rES)
 Layout Direction (Ex. LTR, RTL)
 Orientation (Ex. Portrait, landscape)
 Version (Ex. v14, v7)
 Others are Smallest Screen Width, Screen Widht, Screen
Height, Ratio, UI Mode, Night Mode, Touch Screen,
Keyboard, Text Input, Navigation State, Navigation
Method, Dimension
Drawable Resources
 A drawable resource is a general concept for a
graphic that can be drawn to the screen
 Resource Reference
 In XML: @<package:>drawable/<resource name>
 In Java: <package.>R.drawable.<resource name>
 Drawable Resource Types
 Bitmap (.PNG, .JPG, or .GIF)
 Shape (geometric shapes)
 Nine-Patch (stretchable images, .9.PNG)
 Layer List (a stack/array of drawables)
 State List (multi-state drawables; Ex. On-Off Image)
 Level List (alternative drawables depending on value)
 Transition (crossfaded drawables)
 Others are Inset, Scale, and Clip
String Resources
 Provides text strings for your application with optional
text styling and formatting
 Resource Reference
 In XML: @<package:>string/<resource name>
 In Java: <package.>R.string.<resource name>
 Types
 String (normal text, can be formatted)
 String Arrays (for text arrays)
 Quantity String/Plurals (texts for pluralizations)
 Basic HTML formatting are supported (<b>, <i>, <u>,
etc.)
Layout Resources
 Defines the architecture for the UI in an Activity or a
component of a UI
 Resource Reference for Layout XMLs
 In XML: @<package:>layout/<layout name>
 In Java: <package.>R.layout.<layout name>
 Resource Reference for individual Views/ViewGroups
 In XML: @<package:>id/<layout name>
 In Java: <package.>R.id.<layout name>
 Considerations when using RelativeLayouts
 Preceding Views can be referenced directly
Ex. android:layout_below=“@id/preceedingViewId”
 Succeeding Views must be referenced with the
assumption it is still not created
Ex. android:layout_above=“@+id/succeedingViewId”
Activities and IntentFilters
Activities
 Provides a screen with which users can
interact in order to do something, such as dial
the phone, take a photo, send an email, or
view a map.
 Each activity is given a window in which to
draw its user interface. The window typically
fills the screen, but may be smaller than the
screen and float on top of other windows.
 An application usually consists of multiple
activities that are loosely bound to each
other.
 To create an activity, you must create a
subclass of Activity (or an existing subclass of
it). 
Activities
 There are two methods almost all subclasses of
Activity will implement:
 onCreate(Bundle) - where you initialize your
activity. Most importantly, here you will usually
call setContentView(int) with a layout resource
defining your UI, and using findViewById(int) to
retrieve the widgets in that UI that you need to
interact with programmatically.
 onPause() - is where you deal with the user
leaving your activity. Most importantly, any
changes made by the user should at this point
be committed (usually to the ContentProvider
holding the data).
Activities – Lifecycle
 An activity has essentially four states:
 If an activity in the foreground of the screen
(at the top of the stack), it is active or
running.
 If an activity has lost focus but is still visible
(that is, a new non-full-sized or transparent
activity has focus on top of your activity), it
is paused. A paused activity is completely
alive (it maintains all state and member
information and remains attached to the
window manager), but can be killed by the
system in extreme low memory situations.
Activities – Lifecycle
 An activity has essentially four states:
 If an activity is completely obscured by
another activity, it is stopped. It still retains all
state and member information, however, it is
no longer visible to the user so its window is
hidden and it will often be killed by the system
when memory is needed elsewhere.
 If an activity is paused or stopped, the system
can drop the activity from memory by either
asking it to finish, or simply killing its process.
When it is displayed again to the user, it must
be completely restarted and restored to its
previous state.
Activities – Lifecycle
Activities – Tasks & Backstack
A representation of how each new activity in a task adds an item to
the back stack. When the user presses the Back button, the current
activity is destroyed and the previous activity resumes.
Activities – Tasks & Backstack
 Task
 is a collection of activities that users interact
with when performing a certain job.
 is a cohesive unit that can move to the
"background" when users begin a new task or
go to the Home screen, via the Home button.
 While in the background, all the activities in the
task are stopped, but the back stack for the
task remains intact—the task has simply lost
focus while another task takes place.
 can then return to the "foreground" so users can
pick up where they left off.
Activities – Tasks & Backstack
Two tasks: Task B receives user interaction in the foreground, while
Task A is in the background, waiting to be resumed.
Activities – Starting
 You can start another activity by calling
startActivity(), passing it an Intent that
describes the activity you want to start.
 The intent specifies either the exact
activity you want to start or describes the
type of action you want to perform (and
the system selects the appropriate activity
for you, which can even be from a
different application).
 An intent can also carry small amounts of
data to be used by the activity that is
started.
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
Explicit Intent
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);
Implicit Intent
Activities – Starting
Activity for a result
Activities – Starting
• start the activity by calling
startActivityForResult() (instead of
startActivity()).
• To then receive the result from the subsequent
activity, implement the onActivityResult()
callback method.
• When the subsequent activity is done, it returns
a result in an Intent to your onActivityResult()
method.
Activities - Starting
static final int PICK_CONTACT_REQUEST = 1;  // The request code
...
private void pickContact() {
    Intent pickContactIntent = new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts"));
    pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user
only contacts w/ phone numbers
    startActivityForResult(pickContactIntent,
PICK_CONTACT_REQUEST);
}
The integer argument is a "request code" that identifies your request.
When you receive the result Intent, the callback provides the same
request code so that your app can properly identify the result and
determine how to handle it.
Activities - Starting
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
 
  if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
     
  if (resultCode == RESULT_OK) {
            // The user picked a contact.
            // The Intent's data Uri identifies which contact was selected.
            // Do something with the contact here (bigger example below)
        }
    }
}
Intents
 is a messaging object you can use to
request an action from another app
component.
 Its most significant use is in the launching
of activities, where it can be thought of as
the glue between activities.
 created with an Intent object, which
defines a message to activate either a
specific component or a specific type of
component—an intent can be either
explicit or implicit, respectively.
Intents – Two types
 Explicit - specify the component to start
by name (the fully-qualified class name).
You'll typically use an explicit intent to
start a component in your own app,
because you know the class name of the
activity or service you want to start.
 Implicit - do not name a specific
component, but instead declare a
general action to perform, which allows a
component from another app to handle
it.
Intents – Two types
 When you create an explicit intent to start
an activity or service, the system
immediately starts the app component
specified in the Intent object.
 When you create an implicit intent, the
Android system finds the appropriate
component to start by comparing the
contents of the intent to the intent filters
declared in the manifest file of other apps
on the device.
Intents – Implicit Intent
[1] Activity A creates an Intent with an action description and
passes it to startActivity(). [2] The Android System searches all apps
for an intent filter that matches the intent. When a match is
found, [3] the system starts the matching activity (Activity B) by
invoking its onCreate() method and passing it the Intent
Intents – Intent Filter
 Intent filter - an expression in an app's
manifest file that specifies the type of
intents that the component would like to
receive.
 For instance, by declaring an intent filter for
an activity, you make it possible for other
apps to directly start your activity with a
certain kind of intent. Likewise, if you do not
declare any intent filters for an activity,
then it can be started only with an explicit
intent.
Intents – Intent Filter
 The system may send a given Intent to an
activity if that activity has an intent filter
fulfills the following criteria of the Intent
object:
 Action - A string naming the action to
perform.
 Data - A description of the data associated
with the intent.
 Category - an additional way to
characterize the activity handling the
intent, usually related to the user gesture or
location from which it's started.
Intents – Intent Filter
For example, here's an activity with an intent filter that handles the 
ACTION_SEND intent when the data type is either text or an image:
<activity android:name="ShareActivity">
    <intent-filter>
        <action
android:name="android.intent.action.SEND"/>
        <category
android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="text/plain"/>
        <data android:mimeType="image/*"/>
    </intent-filter>
</activity>
Intents – Intent Filter
<activity android:name="ShareActivity">
    <!-- filter for sending text; accepts SENDTO action with sms URI schemes
-->
    <intent-filter>
        <action android:name="android.intent.action.SENDTO"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:scheme="sms" />
        <data android:scheme="smsto" />
    </intent-filter>
    <!-- filter for sending text or images; accepts SEND action and text or
image data -->
    <intent-filter>
        <action android:name="android.intent.action.SEND"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="image/*"/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>
Working with Services
Android Services
 Is a component which runs in the background without
direct interaction with the user
 Used for repetitive and long running operations, e.g.,
downloads, polling for data
 Is not on a separate process (otherwise explicitly
defined), but is in the same process as the application
 Is not a thread, but rather it works as a decoupled
component that can execute code independent of
other component’s lifecycles
 Forms of Services
 Started – Explicitly started by another component
 Bound – Bound to another component
 Other types of Services
 IntentService
 AIDL
Android Services
“started” Services
 Creating a “started” service
 Extend the Service-class
 Override onCreate if one time initializations are needed
 Override onStartCommand, where the actual work is
done
 Be reminded to call stopService from a component or
stopSelf if from within
 Service Restart Options (returned in onStartCommand)
 Service.START_STICKY – Will restart automatically and call
onStartCommand, however, previous intent data will not be
present
 Service.START_NOT_STICKY – Does not automatically restart
service
 Service.START_REDELIVER_INTENT
“bound” Services
 Creating a “bound” service
 Extend the Service-class
 Override onCreate if one time initializations are needed
 Override onBind and return a valid IBinder-implementor
 Create an instance of ServiceConnection bound services
 Create a common
 Service Restart Options (returned in onStartCommand)
 Service.START_STICKY – Will restart automatically and call
onStartCommand, however, previous intent data will not be
present
 Service.START_NOT_STICKY – Does not automatically restart
service
 Service.START_REDELIVER_INVERSE
IntentService
 A straightforward structure for running an operation
on a single background thread
 Service requests sequentially processed
 Has it’s own worker thread
 Must only override onHandleIntent rather than
startCommand
 Auto start and stop when task are finished
 More ideal for doing simple fire and forget calls like
sending emails or posting a request
BroadcastReceiver
BroadcastReceiver
 is an Android component which allows
you to register for system or application
events. All registered receivers for an
event are notified by the Android runtime
once this event happens.
  applications can register for a particular
event. Once the event occurs, the system
will notify all the registered applications.
 job is to pass a notification to the user, in
case a specific event occurs.
BroadcastReceiver
 Two type of registration
 can be registered via the
AndroidManifest.xml file.
<receiver
android:name="com.example.broadcastreceivertest.Incom
ingSmsReceiver" >
<intent-filter>
<action
android:name="android.provider.Telephony.SMS_RECEIVED
" />
</intent-filter>
</receiver>
BroadcastReceiver
 Two type of registration
 dynamic, which is done using
Context.registerReceiver() method.
Dynamically registered broadcast receivers
can be unregistered using
Context.unregisterReceiver() method.
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
registerReceiver(intentReceiver, intentFilter);
BroadcastReceiver
 Creation
 Extend BroadcastReceiver abstract class.
 Implement onReceive()
 Register to AndroidManifest.xml or in an
Activity.
 You may provide a Notification for the
received result.
For some events we may require permissions. For example to use
<action android:name="android.intent.action.PHONE_STATE" />
We need to add:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
SQLite and ContentProvider
What is SQLite?
 Open-source (Yeah!)
 A full-featured relational database (transactional
etc.)
 Supports standards SQL
 Very lightweight (only ~250KB)
 Fully embeddable (self-contained)
 Dynamically Typed
 No need to setup, just create a database (CREATE-
statements) and Android will manage the rest
(serverless)
 Does I/O in filesystem, so it should be run
asynchronously
 Default location is at /data/data/<you app’s
package name>/dabases/<database’s name>
What is SQLite?
 Storage Classes
 NULL
 INTEGER
 REAL
 TEXT
 BLOB
 Booleans are either “0” or “1” INTEGERs
 Dates/times are TEXT, INTEGER, or REAL
SQLiteDatabase
 Exposes methods to manage a SQLite database
 Has methods to create, delete, execute SQL
commands, and perform other common database
management tasks
 Database names must be unique only within the app,
not across all applications
 Key Methods
 beginTransaction/endTransaction
 query/rawQuery
 execSQL
 update
 delete
 insert
Cursor and ContentValues
 Cursors
 Provides an interface to random read-write access to the
result set returned by a database query
 Similar to your ResultSet in Java (JDBC)
 Common Types
 MergeCursor – Designed to concatenate two data sets
"vertically", adding more rows (like UNION)
 CursorJoiner – Designed to concatenate two data sets
"horizontally", adding more columns (like a SQL JOIN)
 MatrixCursor – Allows you to build something that implements
the Cursor interface out of pure data
 AbstractCursor – Allows you to wrap your own custom data set
in a Cursor interface, overriding the methods that are
necessary
 ContentValues
 A key-value pair data structure for use in SQLiteDatabase
transactions in Android
SQLiteOpenHelper
 A helper class to manage database creation and
version management
 Takes care of opening the database if it exists,
creating it if it does not, and upgrading it as
necessary
 Transactions are used to make sure the database is
always in a sensible state
 Key Methods to Override
 onCreate(sqliteDatabase)
 Called upon first access to the database
 onUpgrade(sqliteDatabase, oldVersion, newVersion)
 Called when current database version differs from a new one
 onOpen(sqliteDatabase)
 Called upon opening a SQLiteDatabase
ContentProvider
 Manages access to a central repository of data
 Primarily intended to be used by other applications,
which access the provider using a provider client
object
 Applications access a ContentProvider data through
a ContentResolver object from a Context
 Data can be accessed or modified via a Content URI
(Ex.
content://com.safeway.client/savings/weeklyads)
ContentProvider
 Manages access to a central repository of data
 Primarily intended to be used by other applications,
which access the provider using a provider client
object
 Applications access a ContentProvider data through
a ContentResolver object from a Context
 Data can be accessed or modified via a Content URI
(Ex.
content://com.safeway.client/savings/weeklyads)
Conventions
SharedPreferences
SharedPreferences
 The SharedPreferences class provides a general
framework that allows you to save and retrieve
persistent key-value pairs of primitive data types.
 data will persist across user sessions (even if your
application is killed).
 Are only for reading & writing key-value pairs
and you should not confuse them with the
Preference APIs, which help you build a user
interface for your app settings (although they use
SharedPreferences as their implementation to
save the app settings).
SharedPreferences
 Two methods to use:
 getSharedPreferences() - Use this if you need
multiple preferences files identified by name, which
you specify with the first parameter.
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString(R.string.preference_file_key),
Context.MODE_PRIVATE);
* opens it using the private mode so the file is accessible by only
your app.
*When naming your shared preference files, you should use a
name that's uniquely identifiable to your app, such as
"com.example.myapp.PREFERENCE_FILE_KEY"
SharedPreferences
 Two methods to use:
 getPreferences() — Use this from an Activity if you
need to use only one shared preference file for the
activity. Because this retrieves a default shared
preference file that belongs to the activity, you
don't need to supply a name.
SharedPreferences sharedPref =
getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences
 Writing a SharedPreference:
 create a SharedPreferences.Editor by calling edit()
on your SharedPreferences.
 Pass the keys and values you want to write with
methods such as putInt() and putString(). Then call
commit() to save the changes.
SharedPreferences sharedPref =
getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score),
newHighScore);
editor.commit();
SharedPreferences
 Read a SharedPreference:
 call methods such as getInt() and getString(),
providing the key for the value you want, and
optionally a default value to return if the key isn't
present
SharedPreferences sharedPref =
getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue =
getResources().getInteger(R.string.saved_high_score_default);
long highScore =
sharedPref.getInt(getString(R.string.saved_high_score),
defaultValue);
Connecting to the Internet
Day II
Connecting to the Internet
 <uses-permission
android:name="android.permission.INTERNET" /
>
 <uses-permission
android:name="android.permission.ACCESS_N
ETWORK_STATE" />
java.net.*
android.net.*
Connecting to the Internet
 Choose an HTTP Client
 HttpURLConnection
 Apache HttpClient
*Both support HTTPS, streaming uploads and
downloads, configurable timeouts, IPv6,
and connection pooling.
*Recommend using HttpURLConnection for
applications targeted at Gingerbread and
higher.
Connecting to the Internet
 Perform Network Operations on a Separate
Thread
 The AsyncTask class provides one of the simplest
ways to fire off a new task from the UI thread.
new LoginTask().execute(params);
Connecting to the Internet
 The AsyncTask class provides one of the
simplest ways to fire off a new task from the UI
thread.
 enables proper and easy use of the UI thread.
 This class allows to perform background
operations and publish results on the UI thread
without having to manipulate threads and/or
handlers.
 designed to be a helper class around Thread
and Handler and does not constitute a generic
threading framework.
Connecting to the Internet
 AsyncTask's generic types:
 Params, the type of the parameters sent to the task
upon execution.
 Progress, the type of the progress units published
during the background computation.
 Result, the type of the result of the background
computation.
Not all types are always used by an asynchronous task. To mark
a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Connecting to the Internet
 AsyncTask's Process:
Connecting to the Internet
4 Steps
onPreExecute(), invoked on the UI thread before the
task is executed. This step is normally used to setup the
task, for instance by showing a progress bar in the user
interface.
Connecting to the Internet
4 Steps
doInBackground(Params...), invoked on the
background thread immediately after onPreExecute()
finishes executing. This step is used to perform
background computation that can take a long time.
The parameters of the asynchronous task are passed to
this step. The result of the computation must be returned
by this step and will be passed back to the last step.
 This step can also use publishProgress(Progress...) to
publish one or more units of progress. These values are
published on the UI thread, in the
onProgressUpdate(Progress...) step.
Connecting to the Internet
4 Steps
onProgressUpdate(Progress...), invoked on the UI
thread after a call to publishProgress(Progress...). The
timing of the execution is undefined. This method is used
to display any form of progress in the user interface
while the background computation is still executing. For
instance, it can be used to animate a progress bar or
show logs in a text field.
Connecting to the Internet
4 Steps
onPostExecute(Result), invoked on the UI thread after
the background computation finishes. The result of the
background computation is passed to this step as a
parameter.
Connecting to the Internet
Threading rules
There are a few threading rules that must be followed for this
class to work properly:
The AsyncTask class must be loaded on the UI thread.
This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result),
doInBackground(Params...),
onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will
be thrown if a second execution is attempted.)
Connecting to the Internet
 Handler
 allows you to send and process Message and
Runnable objects associated with a thread's
MessageQueue.
 Each Handler instance is associated with a single
thread and that thread's message queue.
 When you create a new Handler, it is bound to the
thread / message queue of the thread that is
creating it -- from that point on, it will deliver
messages and runnables to that message queue
and execute them as they come out of the
message queue.
Connecting to the Internet
There are two main uses for a Handler:
to schedule messages and runnables to be
executed at some point in the future; and
to enqueue an action to be performed on a
different thread than your own.
The Android Manifest
The Android Manifest
 Defines components and settings
 Provides additional meta-data for the application
 Ex. icons, app name, or the app version
 Provides certain qualifiers and/or configuration for the
PackageManager/Google Play
 Ex. Minimum Android version the app requires or the
devices that can download and install the app
 It is where you define what permissions, features, or
libraries the application needs and requests
 Ex. Declarion of the app on what 3rd
party system library it
uses or what permission it requires, e.g. INTERNET
AndroidManifest.xml
 Key Elements
 <action>
 <activity>
 <activity-alias>
 <category>
 <data>
 <grant-uri-permission>
 <instrumentation>
 <intent-filter>
 <manifest>
 <uses-sdk>
 <supports-gl-texture>
 <meta-data>
 <permission>
 <permission-group>
 <permission-tree>
 <provider>
 <receiver>
 <service>
 <supports-screens>
 <uses-configuration>
 <uses-feature>
 <uses-permission>
 <compatible-screens>
<manifest>
 The root element of the AndroidManifest.xml file
 It must contain an <application> element and specify
xmlns:android and package attributes
 Key Attributes
 xmlns:android
 Always set to http://schemas.android.com/apk/res/android
 Package
 A full Java-language-style package name for the application
 The name should be unique, as this identifies your application
 android:versionCode
 Internal version number; Rule of thumb would be to follow the
revision no. of the code
 android:versionName
 The version visible to the users
 android:installLocation
 Either “auto”, “internalOnly”, or “preferExternal”
<uses-sdk>
 Allows you to target and specify the applications
desired minimum and/or maximum Android version
 Key Attributes
 minSdkVersion
 Defines the minimum Android version the application can
work on
 Used to filter your device out in Google Play
 If omitted, will assume app will work even on the first version
 targetSdkVersion
 Defines the Android version the application was tested on and
targets
 If omitted, will assume version specified in minSdkVersion
 maxSdkVersion
 Defines the maximum Android version the application can
may work on
 Not recommended anymore as it will be deprecated soon
API Level/Version
 An integer value that uniquely identifies the
framework API revision offered by a version of the
Android platform
<uses-permission>
 Requests a permission that the application must be
granted in order for it to operate correctly
 Permission are granted upon installation
 Key Attributes
 android:name
 The name of the permission
Ex. android.permission.INTERNET or android.permission.CAMERA
 android:maxSdkVersion
 The max version the application will request for a specific
permission
Ex. android.permission.WRITE_EXTERNAL_STORAGE will not be
granted beginning KitKat as it is being
deprecated
<application>
 The declaration of the application
 Where all components must be declared in
 Key Attributes
 android:icon
 The applications icon
 android:label
 The application name
 android:name
 A reference to the apps Application-class
 android:theme
 A reference to a style that the whole application will use
<intent-filter>
 Specifies the types of intents that an activity, service,
or broadcast receiver can respond to
 Declares what the component can handle
 Key Elements
 <action>
 Required
 <category>
 <data>
<action>
 Declares an “action” that a component can handle
 Can be declared multiple times, but recommended is
to decouple and create separate <intent-filter>
 For an intent to pass, must match one of the actions
declared
 Key Attributes
 android:name
 The defined action that the intent can/may handle
 Recommended is to use a package prefixed action
Ex. com.safeway.client.android.ACTION_MYLIST
<category>
 Declares a “action” that a component can handle
 Can be declared multiple times, but recommended is
to decouple and create separate <intent-filter>
 For an intent to pass, all categories declared must be
included in the intent
 Key Attributes
 android:name
 The defined category that the intent can/may handle
 Recommended is to use a package prefixed category
Ex. com.safeway.client.android.CATEGORY_EDIT
<data>
 Declares a “data” or URI or MIME-type the
component can/may handle
 Attributes are optional, but are mutually dependent
<scheme>://<host>:<port>/[<path>]|(other path-attributes)
 Key Attributes
 android:scheme
 Examples are “http” or “tel”
 android:host
 Examples are “com.safeway.client” or a telephone number
 android:port
 Examples are “8080” or “5555”
 android:path
 Examples are “/helloworld” or “/someSubPath”
<activity>
 Declares an activity that implements part of the
application's visual user interface
 Every activity must be declared to shown
 Key Attributes
 android:configChanges
 Lists configuration changes that the activity will handle itself
Ex. orientation or locale
 android:icon
 Activity’s unique icon
 android:label
 Activity’s visible name when in foreground
 android:name
 A reference to the Activity’s implementing class
 android:screenOrientation
 The orientation of the activity's display on the device
<activity>
 Key Attributes (continued)
 android:launchMode
 standard (creation)
 Default. The system always creates a new instance of the activity in
the target task and routes the intent to it.
 singleTop (creation)
 If an instance of the activity already exists at the top of the target
task, the system routes the intent to that instance through a call to its
onNewIntent() method, rather than creating a new instance of the
activity.
 singleTask (task)
 The system creates the activity at the root of a new task and routes
the intent to it. However, if an instance of the activity already exists,
the system routes the intent to existing instance through a call to its
onNewIntent() method, rather than creating a new one.
 singleInstance (task)
 Same as "singleTask", except that the system doesn't launch any
other activities into the task holding the instance. The activity is
always the single and only member of its task.
<service>
 Declares a service (a Service subclass) as one of the
application's components
 Key Attributes
 android:icon
 Service’s unique icon
 android:label
 Service’s visible name when in foreground
 android:name
 A reference to the Service’s implementing class
 android:process
 The name of the process where the service is to run
 If starting with “:”, will create (if necessary) a private process
for the application
 Else, it will create a global process that can be shared
(resource sharing)
<receiver>
 Declares a broadcast receiver (a BroadcastReceiver
subclass) as one of the application's components
 Key Attributes
 android:icon
 BroadcastReceiver’s unique icon
 android:label
 BroadcastReceiver’s visible name when in foreground
 android:name
 A reference to the BroadcastReceiver’s implementing class
 android:enabled
 If enabled, receiver will be able to listen to intents it can
handle
 Default value is “true”
 android:process
<provider>
 Declares a content provider (a ContentProvider
subclass) as one of the application's components
 Key Attributes
 android:authorities
 Used to identify what URIs the content provider offers
 Must declare at least one authority
 android:name
 A reference to the ContentProvider’s implementing class
 android:exported
 Defines if the content provider is accessible by other
applications
 Default value is “true” if on API 16 and below, else default is
“false”
 android:enabled
 android:process
Contacts and Resources
 SDG Mobile Computing – Android Team
 Michael Angelo M. Rivera
 MichaelAngelo.Rivera@safeway.com
 Deuphil B. Kaufmann
 Deuphil.Kaufmann@safeway.com
 Official Android Developer site
 http://developer.android.com
 Safeway Mobile Development Center
 http://collab.safeway.com/it/SDLC/mobile/Lists/androi

More Related Content

What's hot

Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Javaamaankhan
 
Android basic principles
Android basic principlesAndroid basic principles
Android basic principlesHenk Laracker
 
Android development tutorial
Android development tutorialAndroid development tutorial
Android development tutorialnazzf
 
Basic android development
Basic android developmentBasic android development
Basic android developmentUpanya Singh
 
Getting started with android dev and test perspective
Getting started with android   dev and test perspectiveGetting started with android   dev and test perspective
Getting started with android dev and test perspectiveGunjan Kumar
 
Day1 before getting_started
Day1 before getting_startedDay1 before getting_started
Day1 before getting_startedAhsanul Karim
 
Android application development
Android application developmentAndroid application development
Android application developmentMadhuprakashR1
 
Android Studio Overview
Android Studio OverviewAndroid Studio Overview
Android Studio OverviewSalim Hosen
 
Android application structure
Android application structureAndroid application structure
Android application structureAlexey Ustenko
 
Android App Development Intro at ESC SV 2012
Android App Development Intro at ESC SV 2012Android App Development Intro at ESC SV 2012
Android App Development Intro at ESC SV 2012Opersys inc.
 
Android Programming Basics
Android Programming BasicsAndroid Programming Basics
Android Programming BasicsEueung Mulyana
 
Android chapter02-setup2-emulator
Android chapter02-setup2-emulatorAndroid chapter02-setup2-emulator
Android chapter02-setup2-emulatorguru472
 
Ui layout (incomplete)
Ui layout (incomplete)Ui layout (incomplete)
Ui layout (incomplete)Ahsanul Karim
 
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]Sittiphol Phanvilai
 
Mobile Application Development With Android
Mobile Application Development With AndroidMobile Application Development With Android
Mobile Application Development With Androidguest213e237
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesAhsanul Karim
 
Eclipse & android setup
Eclipse & android setupEclipse & android setup
Eclipse & android setupChina Bigs
 
Simple Android Project (SAP)... A Test Application
Simple Android Project (SAP)... A Test ApplicationSimple Android Project (SAP)... A Test Application
Simple Android Project (SAP)... A Test ApplicationAritra Mukherjee
 

What's hot (20)

Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
 
Android basic principles
Android basic principlesAndroid basic principles
Android basic principles
 
Android development tutorial
Android development tutorialAndroid development tutorial
Android development tutorial
 
Basic android development
Basic android developmentBasic android development
Basic android development
 
Getting started with android dev and test perspective
Getting started with android   dev and test perspectiveGetting started with android   dev and test perspective
Getting started with android dev and test perspective
 
PPT Companion to Android
PPT Companion to AndroidPPT Companion to Android
PPT Companion to Android
 
Day1 before getting_started
Day1 before getting_startedDay1 before getting_started
Day1 before getting_started
 
Android application development
Android application developmentAndroid application development
Android application development
 
Android Studio Overview
Android Studio OverviewAndroid Studio Overview
Android Studio Overview
 
Android application structure
Android application structureAndroid application structure
Android application structure
 
Android App Development Intro at ESC SV 2012
Android App Development Intro at ESC SV 2012Android App Development Intro at ESC SV 2012
Android App Development Intro at ESC SV 2012
 
Android Programming Basics
Android Programming BasicsAndroid Programming Basics
Android Programming Basics
 
Android chapter02-setup2-emulator
Android chapter02-setup2-emulatorAndroid chapter02-setup2-emulator
Android chapter02-setup2-emulator
 
Ui layout (incomplete)
Ui layout (incomplete)Ui layout (incomplete)
Ui layout (incomplete)
 
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
 
Mobile Application Development With Android
Mobile Application Development With AndroidMobile Application Development With Android
Mobile Application Development With Android
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through Activities
 
Android Development
Android DevelopmentAndroid Development
Android Development
 
Eclipse & android setup
Eclipse & android setupEclipse & android setup
Eclipse & android setup
 
Simple Android Project (SAP)... A Test Application
Simple Android Project (SAP)... A Test ApplicationSimple Android Project (SAP)... A Test Application
Simple Android Project (SAP)... A Test Application
 

Similar to Android Apps Development Getting Started

Introduction to Andriod
Introduction to AndriodIntroduction to Andriod
Introduction to AndriodKaviarasu D
 
Presentation on Android operating system
Presentation on Android operating systemPresentation on Android operating system
Presentation on Android operating systemSalma Begum
 
presentation2-141101015616-conversion-gate01.pdf
presentation2-141101015616-conversion-gate01.pdfpresentation2-141101015616-conversion-gate01.pdf
presentation2-141101015616-conversion-gate01.pdfimau6
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to androidzeelpatel0504
 
ANDROID MOBILE OPERATING SYSTEM
ANDROID MOBILE OPERATING SYSTEMANDROID MOBILE OPERATING SYSTEM
ANDROID MOBILE OPERATING SYSTEMpreeta sinha
 
Getting started with android
Getting started with androidGetting started with android
Getting started with androidamitgb
 
Android seminar-report-body.doc
Android seminar-report-body.docAndroid seminar-report-body.doc
Android seminar-report-body.docDeepak Yadav
 
Android introduction
Android introductionAndroid introduction
Android introductionmcanotes
 
Ch1 hello, android
Ch1 hello, androidCh1 hello, android
Ch1 hello, androidJehad2012
 
Android : Architecture & Components
Android : Architecture & ComponentsAndroid : Architecture & Components
Android : Architecture & ComponentsAkash Bisariya
 
Android Operating System
Android Operating System Android Operating System
Android Operating System Mehvish Mushtaq
 

Similar to Android Apps Development Getting Started (20)

Android
Android Android
Android
 
Introduction to Andriod
Introduction to AndriodIntroduction to Andriod
Introduction to Andriod
 
Presentation on Android operating system
Presentation on Android operating systemPresentation on Android operating system
Presentation on Android operating system
 
presentation2-141101015616-conversion-gate01.pdf
presentation2-141101015616-conversion-gate01.pdfpresentation2-141101015616-conversion-gate01.pdf
presentation2-141101015616-conversion-gate01.pdf
 
Introduction to Android Environment
Introduction to Android EnvironmentIntroduction to Android Environment
Introduction to Android Environment
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Android By Vipin
Android By VipinAndroid By Vipin
Android By Vipin
 
Android
Android Android
Android
 
01 03 - introduction to android
01  03 - introduction to android01  03 - introduction to android
01 03 - introduction to android
 
ANDROID MOBILE OPERATING SYSTEM
ANDROID MOBILE OPERATING SYSTEMANDROID MOBILE OPERATING SYSTEM
ANDROID MOBILE OPERATING SYSTEM
 
Saminar ppt of
Saminar ppt ofSaminar ppt of
Saminar ppt of
 
Getting started with android
Getting started with androidGetting started with android
Getting started with android
 
Android
AndroidAndroid
Android
 
Android seminar-report-body.doc
Android seminar-report-body.docAndroid seminar-report-body.doc
Android seminar-report-body.doc
 
Android introduction
Android introductionAndroid introduction
Android introduction
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
Ch1 hello, android
Ch1 hello, androidCh1 hello, android
Ch1 hello, android
 
Android : Architecture & Components
Android : Architecture & ComponentsAndroid : Architecture & Components
Android : Architecture & Components
 
Android Presentation
Android PresentationAndroid Presentation
Android Presentation
 
Android Operating System
Android Operating System Android Operating System
Android Operating System
 

More from Michael Angelo Rivera

More from Michael Angelo Rivera (6)

Agile Process - Developers Perspective on Scrum
Agile Process - Developers Perspective on ScrumAgile Process - Developers Perspective on Scrum
Agile Process - Developers Perspective on Scrum
 
Android application development for TresmaxAsia
Android application development for TresmaxAsiaAndroid application development for TresmaxAsia
Android application development for TresmaxAsia
 
Part 2 android application development 101
Part 2 android application development 101Part 2 android application development 101
Part 2 android application development 101
 
Part 1 robot in the making
Part 1 robot in the makingPart 1 robot in the making
Part 1 robot in the making
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Yahoo Web Search Api
Yahoo Web Search ApiYahoo Web Search Api
Yahoo Web Search Api
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

Android Apps Development Getting Started

  • 1. Android Applications Development Getting started on the Android Platform  March 12 – 14, 2014 Prepared By Michael Angelo M. Rivera Deuphil B. Kaufmann
  • 2. Agenda  What’s the Android platform ?  Version History.  Android and beyond (Future)  All about the Android Architecture  Tools and SDK overview.  Hello Android Walkthrough  Android User Interface.
  • 3. Agenda  Activities & Intents  Working with Services  BroadcastReceiver  SQLite and ContentProvider  SharedPreferences  Connecting to the Internet  The Android Manifest
  • 4. Android  OS based on the Linux kernel & designed primarily for touchscreen mobile devices such as smartphones & tablet computers.  Initially developed by Android, Inc., which Google backed financially & later bought in 2005, It was unveiled in 2007 along with the founding of the Open Handset Alliance—a consortium of hardware, software, & telecom companies devoted to advancing open standards for mobile devices.
  • 5. Android  provides a rich application framework that allows you to build innovative apps and games for mobile devices in a Java language environment.  powers hundreds of millions of mobile devices in more than 190 countries around the world.
  • 6. Android  The first publicly available smartphone running Android, the HTC Dream (G1), was released on October 22, 2008
  • 7. Android  As of September 2013, one billion Android devices have been activated
  • 9. History – Android Versions Android 1.5, Cupcake  Introduced: April 30, 2009  Key features in this version of Android: Integration of home screen widgets, support for folders on home screen, stereo Bluetooth support, copy/paste in web browser, video recording and playback.  Notable devices of the day: HTC Hero, T- Mobile G1, T-Mobile Cliq, Samsung Moment, LG Eve, Motorola Backflip
  • 10. History – Android Versions Android 1.6, Donut  Introduced: September 15, 2009  Key features in this version of Android: Quick search box, updated interface for camera, camcorder, and gallery, updated Google Play (Android Market), battery usage indicator, text-to-speech engine,  Notable devices of the day: LG Optimus, Motorola Devour, Samsung Behold II, Samsung Galaxy, Sony Ericsson Xperia X10, Garminfone.
  • 11. History – Android Versions Android 2.0 – 2.1 Eclair  Introduced: October 26, 2009  Key features in this version of Android: Google Maps Navigator (beta), updated browser, support for multiple accounts, improved keyboard, SMS search, Exchange support.  Notable devices of the day: Motorola Droid, Motorola Charm, Motorola Flipout, Samsung Galaxy S, Acer Liquid E, HTC Desire.
  • 12. History – Android Versions Android 2.2 – 2.3 Froyo  Introduced: May 20, 2010  Key features in this version of Android: Support for Adobe Flash, portable hotspots, multiple keyboard languages, speed and performance improvements, enhanced Microsoft Exchange support.  Notable devices of the day: Nexus One, HTC EVO, Droid Incredible, Droid X, Samsung Droid Charge, Sidekick 4G.
  • 13. History – Android Versions Android 2.3 – 2.3.7 Gingerbread  Introduced: December 6, 2010  Key features in this version of Android: UI refinements, NFC support, native support for SIP VOIP, faster/more intuitive text input, enhanced copy and paste.  Notable devices of the day: Nexus S, HTC Sensation, HTC EVO 3D, Motorola Droid Razr, Samsung Galaxy S II, Sony Xperia Play
  • 14. History – Android Versions Android 3.0 – 3.2 Honeycomb  Introduced: February 22, 2011  Key features in this version of Android: Revamped (holographic) UI designed specifically for tablets, action bar, improved multi-tasking, updated standard Android apps, better copy/paste, redesigned keyboard.  Notable devices of the day: Motorola Xoom, Eee Pad Transformer, Samsung Galaxy Tab.
  • 15. History – Android Versions Android 4.0 Ice Cream Sandwich  Introduced: October 19, 2011  Key features in this version of Android: improved multi-tasking, face unlock, resizeable widgets, Android beam, enhanced email options, improved text and voice input, soft buttons can replace hard keys.  Notable devices of the day: Galaxy Nexus, HTC One X, LG Optimus G, Samsung Galaxy Note 10.1, Motorola Droid Razr M, Sony Xperia T.
  • 16. History – Android Versions  Android 4.1 – 4.3 Jelly Bean  Introduced: July 9, 2012  Key features in this version of Android: larger, rich, and actionable notifications, Google Now, offline voice dictation, streamlined UI, performance improvements “Project Butter”, smart widget placement, multi-user profiles for tablets (4.2), lock screen widgets (4.2), daydream (4.2), OpenGL ES 3.0 (4.3), Bluetooth Smart Ready (4.3), restricted user profiles for tablets (4.3).  Notable devices of the day: Samsung Galaxy S3, Samsung Galaxy S4, Samsung Galaxy Note 3, Motorola Moto X, LG G2, Sony Xperia Z, HTC One, Motorola Droid Razr Ultra.
  • 18. Android and beyond Android 4.4 – 4.4.2, KitKat  Introduced: October 23, 2013  Key features in this version of Android: Host Card Emulation,Printing framework,Storage access framework,Low-power sensors,SMS provider,Full-screen Immersive mode,Transitions framework,Chromium WebView,Screen recording,RenderScript NDK,Bluetooth HOGP and MAP,IR Blasters,Closed captioning settings,RTL features,Security enhancements ,Tools for analyzing memory use.
  • 21. Android and beyond Host Card Emulation (HCE)  introduces new platform support for secure NFC-based transactions through Host Card Emulation (HCE), for payments, loyalty programs, card access, transit passes, and other custom services. With HCE, any app on an Android device can emulate an NFC smart card, letting users tap to initiate transactions with an app of their choice
  • 22. Android and beyond IR Blasters  you can build apps that let users remotely control nearby TVs, tuners, switches, and other electronic devices. The API lets your app check whether the phone or tablet has an infrared emitter, query it's carrier frequencies, and then send infrared signals.
  • 24. Android and beyond The Open Automotive Alliance-  is a global alliance of technology and auto industry leaders committed to bringing the Android platform to cars starting in 2014.
  • 26. Android Architecture  Linux Kernel  Relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack and driver model.  The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.
  • 27. Android Architecture  Dalvik Virtual Machine  It is a type of JVM used in android devices to run apps and is optimized for low processing power and low memory environments. Unlike the JVM, the DVM doesn’t run .class files, instead it runs .dex files. .dex files are built from .class file at the time of compilation and provides higher efficiency in low resource environments. The Dalvik VM allows multiple instance of Virtual machine to be created simultaneously providing security, isolation, memory management and threading support. It is developed by Dan Bornstein of Google.
  • 28. Android Architecture  Core Java Libraries  These are different from Java SE and Java ME libraries. However these libraries provides most of the functionalities defined in the Java SE libraries.
  • 29. Android Architecture  A bit more explanation  Java source code is still compiled into .class files. But after .class files are generated, the “dx” tool is used to convert the .class files into a .dex, or Dalvik Executable, file. Whereas a .class file contains only one class, a .dex file contains multiple classes. It is the .dex file that is executed on the Dalvik VM.
  • 30. Android Architecture  Libraries  Android’s native libraries. It is this layer that enables the device to handle different types of data. These libraries are written in c or c++ language and are specific for a particular hardware.
  • 31. Android Architecture  Application Framework  These are the blocks that our applications directly interacts with. These programs manage the basic functions of phone like resource, activity, &voice call management etc. As a developer, you just consider that these are some basic tools with which we are building our applications. Written in Java.
  • 32. Android Architecture  Applications  the top layer in the Android architecture and this is where our applications are going to fit. Several standard applications comes pre-installed with every device, such as: SMS client app, Dialer, Web browser & Contact manager.  As a developer we are able to write an app which replace any existing system app. That is, you are not limited in accessing any particular feature. You are practically limitless and can whatever you want to do with the android (as long as the users of your app permits it). Thus Android is opening endless opportunities to the developer
  • 34. Tools and SDK Overview  Software Requirements  Java Development Kit (JDK), at least JDK 6  http://goo.gl/kCLldE  Eclipse IDE, at least 3.6.2 (Helios)  32-bit - http://goo.gl/RD3wUh  64-bit - http://goo.gl/11uQDQ  ADT Eclipse plug-in  Update Site - https://dl-ssl.google.com/android/eclipse/  Offline - http://goo.gl/BsyGQ1  Android SDK  http://goo.gl/3b0oNG
  • 35. Tools and SDK Overview  Setting up  Install JDK  Install Eclipse  Install ADT (via Update Site or offline package)  Extract the Android SDK to desired install location  Note: Make sure you have the necessary access rights to the install location  Set Android SDK path in Eclipse under Window > Preferences > Android > SDK Location, and select OK  Optional: Add to path to environment, ex. ANDROID_HOME
  • 36. Tools and SDK Overview  Android SDK  AVD Manager – For managing Emulators  SDK Manager – For managing Android Runtimes/Libraries  tools/  DDMS (ddms.bat) – For monitoring devices for debugging  9-Patch Tool (draw9patch.bat)  LINT (lint.bat)  Hierarchy Viewer (hierarchyview.bat)  platform-tools  Android Device Bridge (adb.exe)  Logcat (adb logcat) – For getting system logs
  • 37. Tools and SDK Overview  IDEs  Eclipse  Android ADT Bundle (Eclipse-based)  IntelliJ  AndroidStudio  Build/CI Tools  Ant  Maven  Gradle  Jenkins/Hudson  TravisCI  Testing  Android Instruments (with JUnit)  Robolectric  Robotium
  • 39. Android UI and Resources
  • 40. Densities and Sizes (*cough* fragmentation)
  • 41. Sizes  Actual physical size, measured as the screen's diagonal  There are four generalized sizes: small, normal, large, xlarge
  • 42. Densities  The quantity of pixels within a physical area of the screen  Core densities: low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi) (, and xxhdpi)
  • 44. Android Metrics  Density-independent Pixels (dip/dp)  Screen density independent metric equivalent to 160 dpi  dp = px / (dpi / 160)  Used for View and ViewGroups’ dimensions  Scale-indepedent Pixels (sp)  Similar to dp, but dependent on user font size preferences  Used for text size  Fixed System Attributes  WRAP_CONTENT  FILL_PARENT (deprecated and renamed MATCH_PARENT in API Level 8 and higher)  Pixels (px), Points (pt), (Millimeters) mm, (Inches) in  Don’t you use them even if your life depends on it
  • 45. Building Options  Programmatically (Runtime; Swing-like)  Using XML Layouts (Compiled; Recommended way)
  • 46. Views  The basic building block for UI components  Occupies a rectangular area on the screen and is responsible for drawing and event handling  Get a reference via findViewById(resourceId:int)  Key Views  TextView  EditText  Button  ImageButton  ImageView  RadioButton  CheckBox  Spinner  ProgressBar  ListView
  • 47. Views TextView  Displays text to the user  Key Methods  set-/getText  setTextStyle  setTextSize  setTextColor
  • 48. Views EditText  Inherits from TextView  On top of TextView, it allows it to be editable  Key Methods  Same as TextView
  • 49. Views Button  Represents a push- button  Key Methods/Events  set-/getText  setTextSize  setTextStyle  setEnabled  View.onClickListener
  • 50. Views ImageButton  Same as button, but focused on an image rather on texts  Not a subclass of Button  Key Methods/Events  setImageResource  setImageDrawable  setEnabled  View.OnClickListener
  • 51. Views ImageView  Container for images  No GIFs   Key Methods/Events  setImageResource  setImageDrawable
  • 52. Views CheckBox  Represents a 2-state button, as checked and unchecked only  A subclass of CompoundButton  Key Methods/Events  isChecked  setChecked  toggle  View.OnClickListener
  • 53. Views RadioButton  Represents a 2-state button, as selected and unselected only  A subclass of CompoundButton  For mutual exclusive selection, must be wrapped around a RadioGroup  Key Methods/Events  Same as CheckBox
  • 54. Views ProgressBar  Presents a visual indicator of progress in some operation  Progress can be set incrementally or be set a indeterminate  Key Methods/Events  setProgress  setMax  setIndeterminate
  • 55. Views Spinner  Represents a collapsed dropdown menu of selection  Populate data with an Adapter  Key Methods/Events  AdapterView.OnItemS elected  setAdapter
  • 56. Views ListView  Widget for displaying lists  Populate data with an Adapter  Key Methods/Events  AdapterView.OnItemC lick  AdapterView.OnItemL ongClick  setAdapter
  • 57. Adapters  Bridges the AdapterView (ListView, Spinners etc.)to an underlying data  In charge of creating and managing list item Views  Key/Common Adapter Classes  ArrayAdapter  BaseAdapter  CursorAdapter  SimpleCursorAdapter
  • 58. Adapters - ArrayAdapter  A concrete implementation of BaseAdapter backed by an array of objects  Usage Options  Create an instance directly from an Array-resource via a static method  Create an instance with custom Objects via its constructors
  • 59. Adapters - BaseAdapter  Base class for most Adapter implementations  A good practice is to extend this class rather than relying on ArrayAdapter  This allows your code to be maintained easier as it grows and requirements changes  The implementer doesn’t have to worry how its made as its encapsulated away  Used with the infamous workaround ViewHolder- pattern for optimizing View creations  You may also create a custom View instead of a ViewHolder
  • 60. ViewGroups  A special View that serves as an invisible container to other Views/ViewGroups  Base class for all layouts  Includes an implementation of ViewGroup.LayoutParams, which defines the attributes that affects containing children Views  Key ViewGroups  LinearLayout  RelativeLayout  FrameLayout  ScrollLayout
  • 61. ViewGroup LinearLayout  Is a ViewGroup that aligns all its children Views into a single direction, either vertically or horizontally  Options are LinearLayout.HORIZONTAL and LinearLayout.VERTICAL, default is horizontal  setOrientation-method (programmatically)  android:orientation-attribute (xml)  Supports assigning of “weights” or “importance” to its children  setWeigtSum (programmatically); This sets the total “weight” that can be distributed  android:weightSum-attribute (xml)  android:layout_weight-attribute (xml); This sets the “weight” of the child View in relation to its parent
  • 62. ViewGroup RelativeLayout  Is a ViewGroup that displays its child views in relative positions  Can position Views, relative to its parent (the RelativeLayout) or to its neighbouring Views  Reference to other Views is via an “assumed” resource ID  Sample Attributes  android:layout_below=“@+id/someViewAbove”  android:layout_centerInParent=“true”  android:layout_alignParentBottom=“true”
  • 63. ViewGroup FrameLayout  Is a ViewGroup that displays single Views on a screen  Child positions can be changed with gravity  Child views are drawn in a stack, last items are drawn on top (think z-index)  The size of the FrameLayout is based on the largest child View
  • 64. ViewGroup ScrollView  Is a ViewGroup that wraps its content in a scrollable container  Only 1 child View per ScrollView  Is a subclass of FrameLayout  Never use a ListView with a ScrollView  Scroll-events will collide  The ListView will create a view for every item, defeating the purpose and will cause performance degradation  It’s just plain wrong!
  • 65. OptionsMenu  Represents a menu of common actions on a screen (ex. Help, Settings, etc.)  Pre-Honeycomb (Android 3.0) accessible via hardware menu button  Honeycomb to present will present the menu in the ActionBar  Menu items are defined under the “menu” sub- resource in XML (recommended)  Called “Actions” on Honeycomb and above
  • 66. ContextMenu  Represents a menu that is contextually created, usually on a ListView (ex. Delete, Share, etc.)  Two implementation alternatives  Floating ContextMenu  ActionMode*  Same with OptionsMenu, must be defined in the “menu” sub-resource in XML  Usually triggered via a long item click in a ListView (ex. Long-Hold-To-Delete)
  • 67. Toasts  Provides a small and simple popup to feedback about an operation  Provides only 2 popup durations  TOAST_SHORT – about 3 seconds  TOAST_LONG – about 5 seconds
  • 68. Dialogs  A small window that prompts the user to make a decision or enter additional information  Does not fill the screen and is normally used for modal events that require users to take an action before they can proceed  Cannot exist without a parent Window/Activity  Must ensure to dismiss/de-reference to avoid leaks  Key Classes  AlertDialog  AlertDialog.Builder  ProgressDialog (avoid!)  TimePickerDialog  DatePickerDialog
  • 69. AlertDialogs(.Builder)  A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout  Provides 3 button options, a positive, a negative, and a neutral one  Creation is through AlertDialog.Builder
  • 70. Date-/TimePickerDialog  Provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year)  Helps ensure that your users can pick a time or date that is valid, formatted correctly, and adjusted to the user's locale  Creation is through a constructor
  • 71. Resources  Are external application artifacts and configurations of an Android App  Provides a system to adjust and align with different device configuration, such as localizations, strings, images, UIs, and animations  There are two basic scenarios  A developer will specify default resources that will be used by the platform regardless of device configuration  Example: An animation resource that is common to all device configuration  Or, a developer will specify multiple resources depending on a target set of device configurations  Example: String resources that are for both English and Spanish users or layout resources that has one for portrait and another one for landscape
  • 72. Resources  Resources reside under the “/res”-folder of your project directory  Every resource will have it’s own ID under its namespace (Ex. R.string.hello_worldThe R.java class contains all the generated IDs and only the SDK is able to generate  Usage Examples  In XML @<package name>:<resource type>/<resource name/id> Ex. android:textColor=“@android:color/transparent”  Programmatically (Runtime) <package name>.R.<resource type>.<resource name> Ex. editText.setText(R.string.hello_world)
  • 73. Resources  Key Resource Types  Animation (tweens or frame animations)  Drawable (images PNG (and/or JPG))  Colors (HEX colors)  Layout or UIs (your XML UI layouts)  Menus (your OptionsMenu or ContextMenu resources)  String (external texts and/or text localizations) Arrays (external arrays, such as Email Types) Arrays (text arrays, such as Email Types)  Dimensions (pixels, points, inches, millimetres)  Other Resource Types  Style (UI and/or component themes)  String Plurals (texts for defining plurality, such as “Elf” and “Elves”)  Color State Lists, Booleans, Integers, IDs, TypedArray
  • 74. Resources  Qualifiers  Device Density (Ex. hdpi, xhdpi, mdpi)  Device Size (Ex. normal, large)  Country Code/MCC (Ex. mcc630)  Network Code/MNC (Ex. Mnc610)  Language (Ex. En, Es)  Region (Ex. rUS, rES)  Layout Direction (Ex. LTR, RTL)  Orientation (Ex. Portrait, landscape)  Version (Ex. v14, v7)  Others are Smallest Screen Width, Screen Widht, Screen Height, Ratio, UI Mode, Night Mode, Touch Screen, Keyboard, Text Input, Navigation State, Navigation Method, Dimension
  • 75. Drawable Resources  A drawable resource is a general concept for a graphic that can be drawn to the screen  Resource Reference  In XML: @<package:>drawable/<resource name>  In Java: <package.>R.drawable.<resource name>  Drawable Resource Types  Bitmap (.PNG, .JPG, or .GIF)  Shape (geometric shapes)  Nine-Patch (stretchable images, .9.PNG)  Layer List (a stack/array of drawables)  State List (multi-state drawables; Ex. On-Off Image)  Level List (alternative drawables depending on value)  Transition (crossfaded drawables)  Others are Inset, Scale, and Clip
  • 76. String Resources  Provides text strings for your application with optional text styling and formatting  Resource Reference  In XML: @<package:>string/<resource name>  In Java: <package.>R.string.<resource name>  Types  String (normal text, can be formatted)  String Arrays (for text arrays)  Quantity String/Plurals (texts for pluralizations)  Basic HTML formatting are supported (<b>, <i>, <u>, etc.)
  • 77. Layout Resources  Defines the architecture for the UI in an Activity or a component of a UI  Resource Reference for Layout XMLs  In XML: @<package:>layout/<layout name>  In Java: <package.>R.layout.<layout name>  Resource Reference for individual Views/ViewGroups  In XML: @<package:>id/<layout name>  In Java: <package.>R.id.<layout name>  Considerations when using RelativeLayouts  Preceding Views can be referenced directly Ex. android:layout_below=“@id/preceedingViewId”  Succeeding Views must be referenced with the assumption it is still not created Ex. android:layout_above=“@+id/succeedingViewId”
  • 79. Activities  Provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map.  Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.  An application usually consists of multiple activities that are loosely bound to each other.  To create an activity, you must create a subclass of Activity (or an existing subclass of it). 
  • 80. Activities  There are two methods almost all subclasses of Activity will implement:  onCreate(Bundle) - where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.  onPause() - is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).
  • 81. Activities – Lifecycle  An activity has essentially four states:  If an activity in the foreground of the screen (at the top of the stack), it is active or running.  If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  • 82. Activities – Lifecycle  An activity has essentially four states:  If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.  If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.
  • 84. Activities – Tasks & Backstack A representation of how each new activity in a task adds an item to the back stack. When the user presses the Back button, the current activity is destroyed and the previous activity resumes.
  • 85. Activities – Tasks & Backstack  Task  is a collection of activities that users interact with when performing a certain job.  is a cohesive unit that can move to the "background" when users begin a new task or go to the Home screen, via the Home button.  While in the background, all the activities in the task are stopped, but the back stack for the task remains intact—the task has simply lost focus while another task takes place.  can then return to the "foreground" so users can pick up where they left off.
  • 86. Activities – Tasks & Backstack Two tasks: Task B receives user interaction in the foreground, while Task A is in the background, waiting to be resumed.
  • 87. Activities – Starting  You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start.  The intent specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application).  An intent can also carry small amounts of data to be used by the activity that is started.
  • 88. Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); Explicit Intent Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent); Implicit Intent Activities – Starting
  • 89. Activity for a result Activities – Starting • start the activity by calling startActivityForResult() (instead of startActivity()). • To then receive the result from the subsequent activity, implement the onActivityResult() callback method. • When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.
  • 90. Activities - Starting static final int PICK_CONTACT_REQUEST = 1;  // The request code ... private void pickContact() {     Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));     pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers     startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); } The integer argument is a "request code" that identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
  • 91. Activities - Starting @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     // Check which request we're responding to     if (requestCode == PICK_CONTACT_REQUEST) {         // Make sure the request was successful         if (resultCode == RESULT_OK) {             // The user picked a contact.             // The Intent's data Uri identifies which contact was selected.             // Do something with the contact here (bigger example below)         }     } }
  • 92. Intents  is a messaging object you can use to request an action from another app component.  Its most significant use is in the launching of activities, where it can be thought of as the glue between activities.  created with an Intent object, which defines a message to activate either a specific component or a specific type of component—an intent can be either explicit or implicit, respectively.
  • 93. Intents – Two types  Explicit - specify the component to start by name (the fully-qualified class name). You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start.  Implicit - do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.
  • 94. Intents – Two types  When you create an explicit intent to start an activity or service, the system immediately starts the app component specified in the Intent object.  When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device.
  • 95. Intents – Implicit Intent [1] Activity A creates an Intent with an action description and passes it to startActivity(). [2] The Android System searches all apps for an intent filter that matches the intent. When a match is found, [3] the system starts the matching activity (Activity B) by invoking its onCreate() method and passing it the Intent
  • 96. Intents – Intent Filter  Intent filter - an expression in an app's manifest file that specifies the type of intents that the component would like to receive.  For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.
  • 97. Intents – Intent Filter  The system may send a given Intent to an activity if that activity has an intent filter fulfills the following criteria of the Intent object:  Action - A string naming the action to perform.  Data - A description of the data associated with the intent.  Category - an additional way to characterize the activity handling the intent, usually related to the user gesture or location from which it's started.
  • 98. Intents – Intent Filter For example, here's an activity with an intent filter that handles the  ACTION_SEND intent when the data type is either text or an image: <activity android:name="ShareActivity">     <intent-filter>         <action android:name="android.intent.action.SEND"/>         <category android:name="android.intent.category.DEFAULT"/>         <data android:mimeType="text/plain"/>         <data android:mimeType="image/*"/>     </intent-filter> </activity>
  • 99. Intents – Intent Filter <activity android:name="ShareActivity">     <!-- filter for sending text; accepts SENDTO action with sms URI schemes -->     <intent-filter>         <action android:name="android.intent.action.SENDTO"/>         <category android:name="android.intent.category.DEFAULT"/>         <data android:scheme="sms" />         <data android:scheme="smsto" />     </intent-filter>     <!-- filter for sending text or images; accepts SEND action and text or image data -->     <intent-filter>         <action android:name="android.intent.action.SEND"/>         <category android:name="android.intent.category.DEFAULT"/>         <data android:mimeType="image/*"/>         <data android:mimeType="text/plain"/>     </intent-filter> </activity>
  • 101. Android Services  Is a component which runs in the background without direct interaction with the user  Used for repetitive and long running operations, e.g., downloads, polling for data  Is not on a separate process (otherwise explicitly defined), but is in the same process as the application  Is not a thread, but rather it works as a decoupled component that can execute code independent of other component’s lifecycles  Forms of Services  Started – Explicitly started by another component  Bound – Bound to another component  Other types of Services  IntentService  AIDL
  • 103. “started” Services  Creating a “started” service  Extend the Service-class  Override onCreate if one time initializations are needed  Override onStartCommand, where the actual work is done  Be reminded to call stopService from a component or stopSelf if from within  Service Restart Options (returned in onStartCommand)  Service.START_STICKY – Will restart automatically and call onStartCommand, however, previous intent data will not be present  Service.START_NOT_STICKY – Does not automatically restart service  Service.START_REDELIVER_INTENT
  • 104. “bound” Services  Creating a “bound” service  Extend the Service-class  Override onCreate if one time initializations are needed  Override onBind and return a valid IBinder-implementor  Create an instance of ServiceConnection bound services  Create a common  Service Restart Options (returned in onStartCommand)  Service.START_STICKY – Will restart automatically and call onStartCommand, however, previous intent data will not be present  Service.START_NOT_STICKY – Does not automatically restart service  Service.START_REDELIVER_INVERSE
  • 105. IntentService  A straightforward structure for running an operation on a single background thread  Service requests sequentially processed  Has it’s own worker thread  Must only override onHandleIntent rather than startCommand  Auto start and stop when task are finished  More ideal for doing simple fire and forget calls like sending emails or posting a request
  • 107. BroadcastReceiver  is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.   applications can register for a particular event. Once the event occurs, the system will notify all the registered applications.  job is to pass a notification to the user, in case a specific event occurs.
  • 108. BroadcastReceiver  Two type of registration  can be registered via the AndroidManifest.xml file. <receiver android:name="com.example.broadcastreceivertest.Incom ingSmsReceiver" > <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED " /> </intent-filter> </receiver>
  • 109. BroadcastReceiver  Two type of registration  dynamic, which is done using Context.registerReceiver() method. Dynamically registered broadcast receivers can be unregistered using Context.unregisterReceiver() method. intentFilter = new IntentFilter(); intentFilter.addAction("SMS_RECEIVED_ACTION"); registerReceiver(intentReceiver, intentFilter);
  • 110. BroadcastReceiver  Creation  Extend BroadcastReceiver abstract class.  Implement onReceive()  Register to AndroidManifest.xml or in an Activity.  You may provide a Notification for the received result. For some events we may require permissions. For example to use <action android:name="android.intent.action.PHONE_STATE" /> We need to add: <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  • 112. What is SQLite?  Open-source (Yeah!)  A full-featured relational database (transactional etc.)  Supports standards SQL  Very lightweight (only ~250KB)  Fully embeddable (self-contained)  Dynamically Typed  No need to setup, just create a database (CREATE- statements) and Android will manage the rest (serverless)  Does I/O in filesystem, so it should be run asynchronously  Default location is at /data/data/<you app’s package name>/dabases/<database’s name>
  • 113. What is SQLite?  Storage Classes  NULL  INTEGER  REAL  TEXT  BLOB  Booleans are either “0” or “1” INTEGERs  Dates/times are TEXT, INTEGER, or REAL
  • 114. SQLiteDatabase  Exposes methods to manage a SQLite database  Has methods to create, delete, execute SQL commands, and perform other common database management tasks  Database names must be unique only within the app, not across all applications  Key Methods  beginTransaction/endTransaction  query/rawQuery  execSQL  update  delete  insert
  • 115. Cursor and ContentValues  Cursors  Provides an interface to random read-write access to the result set returned by a database query  Similar to your ResultSet in Java (JDBC)  Common Types  MergeCursor – Designed to concatenate two data sets "vertically", adding more rows (like UNION)  CursorJoiner – Designed to concatenate two data sets "horizontally", adding more columns (like a SQL JOIN)  MatrixCursor – Allows you to build something that implements the Cursor interface out of pure data  AbstractCursor – Allows you to wrap your own custom data set in a Cursor interface, overriding the methods that are necessary  ContentValues  A key-value pair data structure for use in SQLiteDatabase transactions in Android
  • 116. SQLiteOpenHelper  A helper class to manage database creation and version management  Takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary  Transactions are used to make sure the database is always in a sensible state  Key Methods to Override  onCreate(sqliteDatabase)  Called upon first access to the database  onUpgrade(sqliteDatabase, oldVersion, newVersion)  Called when current database version differs from a new one  onOpen(sqliteDatabase)  Called upon opening a SQLiteDatabase
  • 117. ContentProvider  Manages access to a central repository of data  Primarily intended to be used by other applications, which access the provider using a provider client object  Applications access a ContentProvider data through a ContentResolver object from a Context  Data can be accessed or modified via a Content URI (Ex. content://com.safeway.client/savings/weeklyads)
  • 118. ContentProvider  Manages access to a central repository of data  Primarily intended to be used by other applications, which access the provider using a provider client object  Applications access a ContentProvider data through a ContentResolver object from a Context  Data can be accessed or modified via a Content URI (Ex. content://com.safeway.client/savings/weeklyads)
  • 121. SharedPreferences  The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.  data will persist across user sessions (even if your application is killed).  Are only for reading & writing key-value pairs and you should not confuse them with the Preference APIs, which help you build a user interface for your app settings (although they use SharedPreferences as their implementation to save the app settings).
  • 122. SharedPreferences  Two methods to use:  getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter. Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences(         getString(R.string.preference_file_key), Context.MODE_PRIVATE); * opens it using the private mode so the file is accessible by only your app. *When naming your shared preference files, you should use a name that's uniquely identifiable to your app, such as "com.example.myapp.PREFERENCE_FILE_KEY"
  • 123. SharedPreferences  Two methods to use:  getPreferences() — Use this from an Activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name. SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
  • 124. SharedPreferences  Writing a SharedPreference:  create a SharedPreferences.Editor by calling edit() on your SharedPreferences.  Pass the keys and values you want to write with methods such as putInt() and putString(). Then call commit() to save the changes. SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.saved_high_score), newHighScore); editor.commit();
  • 125. SharedPreferences  Read a SharedPreference:  call methods such as getInt() and getString(), providing the key for the value you want, and optionally a default value to return if the key isn't present SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); int defaultValue = getResources().getInteger(R.string.saved_high_score_default); long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
  • 126. Connecting to the Internet Day II
  • 127. Connecting to the Internet  <uses-permission android:name="android.permission.INTERNET" / >  <uses-permission android:name="android.permission.ACCESS_N ETWORK_STATE" /> java.net.* android.net.*
  • 128. Connecting to the Internet  Choose an HTTP Client  HttpURLConnection  Apache HttpClient *Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling. *Recommend using HttpURLConnection for applications targeted at Gingerbread and higher.
  • 129. Connecting to the Internet  Perform Network Operations on a Separate Thread  The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. new LoginTask().execute(params);
  • 130. Connecting to the Internet  The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.  enables proper and easy use of the UI thread.  This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.  designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.
  • 131. Connecting to the Internet  AsyncTask's generic types:  Params, the type of the parameters sent to the task upon execution.  Progress, the type of the progress units published during the background computation.  Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void: private class MyTask extends AsyncTask<Void, Void, Void> { ... }
  • 132. Connecting to the Internet  AsyncTask's Process:
  • 133. Connecting to the Internet 4 Steps onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  • 134. Connecting to the Internet 4 Steps doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step.  This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  • 135. Connecting to the Internet 4 Steps onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  • 136. Connecting to the Internet 4 Steps onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
  • 137. Connecting to the Internet Threading rules There are a few threading rules that must be followed for this class to work properly: The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN. The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)
  • 138. Connecting to the Internet  Handler  allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.  Each Handler instance is associated with a single thread and that thread's message queue.  When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
  • 139. Connecting to the Internet There are two main uses for a Handler: to schedule messages and runnables to be executed at some point in the future; and to enqueue an action to be performed on a different thread than your own.
  • 141. The Android Manifest  Defines components and settings  Provides additional meta-data for the application  Ex. icons, app name, or the app version  Provides certain qualifiers and/or configuration for the PackageManager/Google Play  Ex. Minimum Android version the app requires or the devices that can download and install the app  It is where you define what permissions, features, or libraries the application needs and requests  Ex. Declarion of the app on what 3rd party system library it uses or what permission it requires, e.g. INTERNET
  • 142. AndroidManifest.xml  Key Elements  <action>  <activity>  <activity-alias>  <category>  <data>  <grant-uri-permission>  <instrumentation>  <intent-filter>  <manifest>  <uses-sdk>  <supports-gl-texture>  <meta-data>  <permission>  <permission-group>  <permission-tree>  <provider>  <receiver>  <service>  <supports-screens>  <uses-configuration>  <uses-feature>  <uses-permission>  <compatible-screens>
  • 143. <manifest>  The root element of the AndroidManifest.xml file  It must contain an <application> element and specify xmlns:android and package attributes  Key Attributes  xmlns:android  Always set to http://schemas.android.com/apk/res/android  Package  A full Java-language-style package name for the application  The name should be unique, as this identifies your application  android:versionCode  Internal version number; Rule of thumb would be to follow the revision no. of the code  android:versionName  The version visible to the users  android:installLocation  Either “auto”, “internalOnly”, or “preferExternal”
  • 144. <uses-sdk>  Allows you to target and specify the applications desired minimum and/or maximum Android version  Key Attributes  minSdkVersion  Defines the minimum Android version the application can work on  Used to filter your device out in Google Play  If omitted, will assume app will work even on the first version  targetSdkVersion  Defines the Android version the application was tested on and targets  If omitted, will assume version specified in minSdkVersion  maxSdkVersion  Defines the maximum Android version the application can may work on  Not recommended anymore as it will be deprecated soon
  • 145. API Level/Version  An integer value that uniquely identifies the framework API revision offered by a version of the Android platform
  • 146. <uses-permission>  Requests a permission that the application must be granted in order for it to operate correctly  Permission are granted upon installation  Key Attributes  android:name  The name of the permission Ex. android.permission.INTERNET or android.permission.CAMERA  android:maxSdkVersion  The max version the application will request for a specific permission Ex. android.permission.WRITE_EXTERNAL_STORAGE will not be granted beginning KitKat as it is being deprecated
  • 147. <application>  The declaration of the application  Where all components must be declared in  Key Attributes  android:icon  The applications icon  android:label  The application name  android:name  A reference to the apps Application-class  android:theme  A reference to a style that the whole application will use
  • 148. <intent-filter>  Specifies the types of intents that an activity, service, or broadcast receiver can respond to  Declares what the component can handle  Key Elements  <action>  Required  <category>  <data>
  • 149. <action>  Declares an “action” that a component can handle  Can be declared multiple times, but recommended is to decouple and create separate <intent-filter>  For an intent to pass, must match one of the actions declared  Key Attributes  android:name  The defined action that the intent can/may handle  Recommended is to use a package prefixed action Ex. com.safeway.client.android.ACTION_MYLIST
  • 150. <category>  Declares a “action” that a component can handle  Can be declared multiple times, but recommended is to decouple and create separate <intent-filter>  For an intent to pass, all categories declared must be included in the intent  Key Attributes  android:name  The defined category that the intent can/may handle  Recommended is to use a package prefixed category Ex. com.safeway.client.android.CATEGORY_EDIT
  • 151. <data>  Declares a “data” or URI or MIME-type the component can/may handle  Attributes are optional, but are mutually dependent <scheme>://<host>:<port>/[<path>]|(other path-attributes)  Key Attributes  android:scheme  Examples are “http” or “tel”  android:host  Examples are “com.safeway.client” or a telephone number  android:port  Examples are “8080” or “5555”  android:path  Examples are “/helloworld” or “/someSubPath”
  • 152. <activity>  Declares an activity that implements part of the application's visual user interface  Every activity must be declared to shown  Key Attributes  android:configChanges  Lists configuration changes that the activity will handle itself Ex. orientation or locale  android:icon  Activity’s unique icon  android:label  Activity’s visible name when in foreground  android:name  A reference to the Activity’s implementing class  android:screenOrientation  The orientation of the activity's display on the device
  • 153. <activity>  Key Attributes (continued)  android:launchMode  standard (creation)  Default. The system always creates a new instance of the activity in the target task and routes the intent to it.  singleTop (creation)  If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.  singleTask (task)  The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.  singleInstance (task)  Same as "singleTask", except that the system doesn't launch any other activities into the task holding the instance. The activity is always the single and only member of its task.
  • 154. <service>  Declares a service (a Service subclass) as one of the application's components  Key Attributes  android:icon  Service’s unique icon  android:label  Service’s visible name when in foreground  android:name  A reference to the Service’s implementing class  android:process  The name of the process where the service is to run  If starting with “:”, will create (if necessary) a private process for the application  Else, it will create a global process that can be shared (resource sharing)
  • 155. <receiver>  Declares a broadcast receiver (a BroadcastReceiver subclass) as one of the application's components  Key Attributes  android:icon  BroadcastReceiver’s unique icon  android:label  BroadcastReceiver’s visible name when in foreground  android:name  A reference to the BroadcastReceiver’s implementing class  android:enabled  If enabled, receiver will be able to listen to intents it can handle  Default value is “true”  android:process
  • 156. <provider>  Declares a content provider (a ContentProvider subclass) as one of the application's components  Key Attributes  android:authorities  Used to identify what URIs the content provider offers  Must declare at least one authority  android:name  A reference to the ContentProvider’s implementing class  android:exported  Defines if the content provider is accessible by other applications  Default value is “true” if on API 16 and below, else default is “false”  android:enabled  android:process
  • 157. Contacts and Resources  SDG Mobile Computing – Android Team  Michael Angelo M. Rivera  MichaelAngelo.Rivera@safeway.com  Deuphil B. Kaufmann  Deuphil.Kaufmann@safeway.com  Official Android Developer site  http://developer.android.com  Safeway Mobile Development Center  http://collab.safeway.com/it/SDLC/mobile/Lists/androi

Editor's Notes

  1. Platform VersionAPI Level Android 4.419KITKAT Android 4.318JELLY_BEAN_MR2 Android 4.2, 4.2.217JELLY_BEAN_MR1 Android 4.1, 4.1.116JELLY_BEAN Android 4.0.3, 4.0.415ICE_CREAM_SANDWICH_MR1 Android 4.0, 4.0.1, 4.0.214ICE_CREAM_SANDWICH Android 3.213HONEYCOMB_MR2 Android 3.1.x12HONEYCOMB_MR1 Android 3.0.x11HONEYCOMB Android 2.3.4 Android 2.3.310GINGERBREAD_MR1 Android 2.3.2 Android 2.3.1 Android 2.39GINGERBREAD Android 2.2.x8FROYO Android 2.1.x7ECLAIR_MR1 Android 2.0.16ECLAIR_0_1 Android 2.05ECLAIR Android 1.64DONUT Android 1.53CUPCAKE Android 1.12BASE_1_1 Android 1.01BASE
  2. As of this writing, Android Studio is still in Early Access Preview and Eclipse ADT Bundle have caused issues some plug-ins
  3. Just an example on how it should and be like. Consistent, consistent, consistent!
  4. What are DIPs? A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a &amp;quot;medium&amp;quot; density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application&amp;apos;s UI, to ensure proper display of your UI on screens with different densities.
  5. Go make a sample UI with TextView saying “Hello World!” in XML
  6. class SampleBaseAdapter extends BaseAdapter { private LayoutInflater layoutInflater; private final String[] listItems = new String[] { &amp;quot;Item 1&amp;quot;, &amp;quot;Item 2&amp;quot;, &amp;quot;Item 3&amp;quot; }; public SampleBaseAdapter() {} public SampleBaseAdapter(Context context) { layoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return listItems.length; } @Override public Object getItem(int position) { return listItems[position]; } @Override public long getItemId(int position) { return listItems[position].hashCode(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = layoutInflater.inflate( android.R.layout.simple_list_item_1, null); viewHolder = new ViewHolder(); viewHolder.titleText = (TextView) convertView .findViewById(android.R.id.text1); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.titleText.setText(listItems[position]); return convertView; } class ViewHolder { TextView titleText; } } ViewHolder or make a custom View
  7. Make sample form!
  8. Make sample form!
  9. &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;&amp;lt;resources&amp;gt;    &amp;lt;plurals name=&amp;quot;numberOfSongsAvailable&amp;quot;&amp;gt;        &amp;lt;item quantity=&amp;quot;one&amp;quot;&amp;gt;Znaleziono jedną piosenkę.&amp;lt;/item&amp;gt;        &amp;lt;item quantity=&amp;quot;few&amp;quot;&amp;gt;Znaleziono %d piosenki.&amp;lt;/item&amp;gt;        &amp;lt;item quantity=&amp;quot;other&amp;quot;&amp;gt;Znaleziono %d piosenek.&amp;lt;/item&amp;gt;    &amp;lt;/plurals&amp;gt;&amp;lt;/resources&amp;gt; int count = getNumberOfsongsAvailable();Resources res = getResources();String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count) Resources res = getResources();String text = String.format(res.getString(R.string.welcome_messages), username, mailCount); &amp;lt;string name=&amp;quot;welcome_messages&amp;quot;&amp;gt;Hello, %1$s! You have %2$d new messages.&amp;lt;/string&amp;gt;
  10. package com.safeway.sampleserviceusage; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindService(new Intent(this, SampleService.class), serviceConnection , Context.BIND_AUTO_CREATE); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: if (sampleService != null) { sampleService.showMessage(&amp;quot;Hello &amp;quot; + System.currentTimeMillis()); } return true; default: return super.onOptionsItemSelected(item); } } private SampleService sampleService; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { sampleService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { sampleService = ((SampleService.SampleBinder) service).getService(); } }; }
  11. Disadvantages of using Java threads in Android If you use Java threads you have to handle the following requirements Synchronization with the main thread if you post back results to the user interface No default for canceling the thread No default thread pooling No default for handling configuration changes in Android
  12. Cancelling a task A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method,onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
  13. Cancelling a task A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method,onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
  14. Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message),sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler&amp;apos;s handleMessage(Message)method (requiring that you implement a subclass of Handler).
  15. standard – multiple instances singleTop – can have multiple instances, but if target is on top, will create nothing singleTask – creates a new task, similar to singleTop singleInstance - similar to singleTask, but only one, and only one, can exist