android applications development

157
Android Applications Development Getting started on the Android Platform March 12 – 14, 2014 Prepared By Michael Angelo M. Rivera Deuphil B. Kaufmann

Upload: michael-angelo-rivera

Post on 19-May-2015

1.066 views

Category:

Technology


1 download

DESCRIPTION

get started developing

TRANSCRIPT

Page 1: Android Applications Development

Android Applications DevelopmentGetting started on the Android Platform 

March 12 – 14, 2014

Prepared ByMichael Angelo M. RiveraDeuphil B. Kaufmann

Page 2: Android Applications Development

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.

Page 3: Android Applications Development

Agenda

Activities & Intents Working with Services BroadcastReceiver SQLite and ContentProvider SharedPreferences Connecting to the Internet The Android Manifest

Page 4: Android Applications Development

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.

Page 5: Android Applications Development

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.

Page 6: Android Applications Development

Android The first publicly available smartphone

running Android, the HTC Dream (G1), was released on October 22, 2008

Page 7: Android Applications Development

Android As of September 2013, one billion

Android devices have been activated

Page 8: Android Applications Development

History – Android Versions

Page 9: Android Applications Development

History – Android VersionsAndroid 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

Page 10: Android Applications Development

History – Android VersionsAndroid 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.

Page 11: Android Applications Development

History – Android VersionsAndroid 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.

Page 12: Android Applications Development

History – Android VersionsAndroid 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.

Page 13: Android Applications Development

History – Android VersionsAndroid 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

Page 14: Android Applications Development

History – Android VersionsAndroid 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.

Page 15: Android Applications Development

History – Android VersionsAndroid 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.

Page 16: Android Applications Development

History – Android VersionsAndroid 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.

Page 17: Android Applications Development

Android and beyond

Page 18: Android Applications Development

Android and beyondAndroid 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.

Page 19: Android Applications Development

Android and beyond

Page 20: Android Applications Development

Android and beyond

Page 21: Android Applications Development

Android and beyondHost 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

Page 22: Android Applications Development

Android and beyondIR 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.

Page 23: Android Applications Development

Android and beyondWearables

Page 24: Android Applications Development

Android and beyondThe Open Automotive Alliance-

is a global alliance of technology and auto industry leaders committed to bringing the Android platform to cars starting in 2014.

Page 25: Android Applications Development

Android Architecture

Page 26: Android Applications Development

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.

Page 27: Android Applications Development

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.

Page 28: Android Applications Development

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.

Page 29: Android Applications Development

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.

Page 30: Android Applications Development

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.

Page 31: Android Applications Development

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.

Page 32: Android Applications Development

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

Page 33: Android Applications Development

Tools and SDK

Page 34: Android Applications Development

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

Page 35: Android Applications Development

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

Page 36: Android Applications Development

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

Page 37: Android Applications Development

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

Page 38: Android Applications Development

Hello Android Walkthrough

Page 39: Android Applications Development

Android UI and Resources

Page 40: Android Applications Development

Densities and Sizes (*cough* fragmentation)

Page 41: Android Applications Development

Sizes Actual physical size, measured as the

screen's diagonal There are four generalized sizes: small,

normal, large, xlarge

Page 42: Android Applications Development

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)

Page 43: Android Applications Development

Densities

BAD!

GOOD!

Page 44: Android Applications Development

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

Page 45: Android Applications Development

Building Options Programmatically (Runtime; Swing-like)

Using XML Layouts (Compiled; Recommended way)

Page 46: Android Applications Development

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

Page 47: Android Applications Development

ViewsTextView Displays text to the

user Key Methods

set-/getText setTextStyle setTextSize setTextColor

Page 48: Android Applications Development

ViewsEditText Inherits from

TextView On top of TextView, it

allows it to be editable Key Methods

Same as TextView

Page 49: Android Applications Development

ViewsButton Represents a push-

button Key Methods/Events

set-/getText setTextSize setTextStyle setEnabled View.onClickListener

Page 50: Android Applications Development

ViewsImageButton Same as button, but

focused on an image rather on texts

Not a subclass of Button

Key Methods/Events setImageResource setImageDrawable setEnabled View.OnClickListener

Page 51: Android Applications Development

ViewsImageView Container for images No GIFs Key Methods/Events

setImageResource setImageDrawable

Page 52: Android Applications Development

ViewsCheckBox Represents a 2-state

button, as checked and unchecked only

A subclass of CompoundButton

Key Methods/Events isChecked setChecked toggle View.OnClickListener

Page 53: Android Applications Development

ViewsRadioButton 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

Page 54: Android Applications Development

ViewsProgressBar 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

Page 55: Android Applications Development

ViewsSpinner Represents a

collapsed dropdown menu of selection

Populate data with an Adapter

Key Methods/Events AdapterView.OnItemS

elected setAdapter

Page 56: Android Applications Development

ViewsListView Widget for displaying

lists Populate data with an

Adapter Key Methods/Events

AdapterView.OnItemClick

AdapterView.OnItemLongClick

setAdapter

Page 57: Android Applications Development

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

Page 58: Android Applications Development

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

Page 59: Android Applications Development

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

Page 60: Android Applications Development

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

Page 61: Android Applications Development

ViewGroupLinearLayout 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

Page 62: Android Applications Development

ViewGroupRelativeLayout 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”

Page 63: Android Applications Development

ViewGroupFrameLayout 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

Page 64: Android Applications Development

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

Page 65: Android Applications Development

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

Page 66: Android Applications Development

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)

Page 67: Android Applications Development

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

Page 68: Android Applications Development

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

Page 69: Android Applications Development

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

Page 70: Android Applications Development

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

Page 71: Android Applications Development

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

Page 72: Android Applications Development

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)

Page 73: Android Applications Development

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

Page 74: Android Applications Development

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

Page 75: Android Applications Development

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

Page 76: Android Applications Development

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

Page 77: Android Applications Development

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”

Page 78: Android Applications Development

Activities and IntentFilters

Page 79: Android Applications Development

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

Page 80: Android Applications Development

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

Page 81: Android Applications Development

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.

Page 82: Android Applications Development

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.

Page 83: Android Applications Development

Activities – Lifecycle

Page 84: Android Applications Development

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.

Page 85: Android Applications Development

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.

Page 86: Android Applications Development

Activities – Tasks & Backstack

Two tasks: Task B receives user interaction in the foreground, while Task A is in the background, waiting to be resumed.

Page 87: Android Applications Development

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.

Page 88: Android Applications Development

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

Page 89: Android Applications Development

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.

Page 90: Android Applications Development

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

Page 91: Android Applications Development

Activities - Starting@Overrideprotected 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)        }    }}

Page 92: Android Applications Development

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.

Page 93: Android Applications Development

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.

Page 94: Android Applications Development

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.

Page 95: Android Applications Development

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

Page 96: Android Applications Development

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.

Page 97: Android Applications Development

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.

Page 98: Android Applications Development

Intents – Intent FilterFor 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>

Page 99: Android Applications Development

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>

Page 100: Android Applications Development

Working with Services

Page 101: Android Applications Development

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

Page 102: Android Applications Development

Android Services

Page 103: Android Applications Development

“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

Page 104: Android Applications Development

“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

Page 105: Android Applications Development

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

Page 106: Android Applications Development

BroadcastReceiver

Page 107: Android Applications Development

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.

Page 108: Android Applications Development

BroadcastReceiver Two type of registration

can be registered via the AndroidManifest.xml file.

<receiver android:name="com.example.broadcastreceivertest.IncomingSmsReceiver" ><intent-filter>

<action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter></receiver>

Page 109: Android Applications Development

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

Page 110: Android Applications Development

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

Page 111: Android Applications Development

SQLite and ContentProvider

Page 112: Android Applications Development

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>

Page 113: Android Applications Development

What is SQLite? Storage Classes

NULL INTEGER REAL TEXT BLOB

Booleans are either “0” or “1” INTEGERs Dates/times are TEXT, INTEGER, or REAL

Page 114: Android Applications Development

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

Page 115: Android Applications Development

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

Page 116: Android Applications Development

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

Page 117: Android Applications Development

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)

Page 118: Android Applications Development

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)

Page 119: Android Applications Development

Conventions

Page 120: Android Applications Development

SharedPreferences

Page 121: Android Applications Development

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

Page 122: Android Applications Development

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"

Page 123: Android Applications Development

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

Page 124: Android Applications Development

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

Page 125: Android Applications Development

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

Page 126: Android Applications Development

Connecting to the InternetDay II

Page 127: Android Applications Development

Connecting to the Internet <uses-permission

android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

java.net.*android.net.*

Page 128: Android Applications Development

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.

Page 129: Android Applications Development

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

Page 130: Android Applications Development

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.

Page 131: Android Applications Development

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

Page 132: Android Applications Development

Connecting to the Internet AsyncTask's Process:

Page 133: Android Applications Development

Connecting to the Internet4 StepsonPreExecute(), 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.

Page 134: Android Applications Development

Connecting to the Internet4 StepsdoInBackground(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.

Page 135: Android Applications Development

Connecting to the Internet4 StepsonProgressUpdate(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.

Page 136: Android Applications Development

Connecting to the Internet4 StepsonPostExecute(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.

Page 137: Android Applications Development

Connecting to the InternetThreading rulesThere 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.)

Page 138: Android Applications Development

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.

Page 139: Android Applications Development

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.

Page 140: Android Applications Development

The Android Manifest

Page 141: Android Applications Development

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

Page 142: Android Applications Development

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>

Page 143: Android Applications Development

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

Page 144: Android Applications Development

<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

Page 145: Android Applications Development

API Level/Version An integer value that uniquely identifies the

framework API revision offered by a version of the Android platform

Page 146: Android Applications Development

<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

permissionEx. android.permission.WRITE_EXTERNAL_STORAGE will not be granted beginning KitKat as it is being deprecated

Page 147: Android Applications Development

<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

Page 148: Android Applications Development

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

Page 149: Android Applications Development

<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

Page 150: Android Applications Development

<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

Page 151: Android Applications Development

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

Page 152: Android Applications Development

<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

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

Page 153: Android Applications Development

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

Page 154: Android Applications Development

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

Page 155: Android Applications Development

<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

Page 156: Android Applications Development

<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

Page 157: Android Applications Development

Contacts and Resources SDG Mobile Computing – Android Team

Michael Angelo M. Rivera [email protected]

Deuphil B. Kaufmann [email protected]

Official Android Developer site http://developer.android.com

Safeway Mobile Development Center http://collab.safeway.com/it/SDLC/mobile/

Lists/androidStart/AllItems.aspx