98
Android Programming 101 for NTU Workshop 2013

Android Workshop 2013

Embed Size (px)

DESCRIPTION

A 1 day NTU workshop for kickstarting Android development. Includes using the newest & better IDE - Android Studio - and a thorough process from developing you idea > mockup > coding > polishing > distributing.

Citation preview

Page 1: Android Workshop 2013

Android Programming 101for NTU Workshop 2013

About Me

Name

Work at

No of apps

Find me at

Junda Ong

Hoiio

20+

just2mecom samwizecom

samwize G+

Hoiio API

Hoiio Business Communication

Hoiio Phone

My Hobby Projects

txeet

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 2: Android Workshop 2013

About Me

Name

Work at

No of apps

Find me at

Junda Ong

Hoiio

20+

just2mecom samwizecom

samwize G+

Hoiio API

Hoiio Business Communication

Hoiio Phone

My Hobby Projects

txeet

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 3: Android Workshop 2013

Hoiio API

Hoiio Business Communication

Hoiio Phone

My Hobby Projects

txeet

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 4: Android Workshop 2013

Hoiio Business Communication

Hoiio Phone

My Hobby Projects

txeet

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 5: Android Workshop 2013

Hoiio Phone

My Hobby Projects

txeet

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 6: Android Workshop 2013

My Hobby Projects

txeet

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 7: Android Workshop 2013

txeet

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 8: Android Workshop 2013

SG 4D

BAD Example of Porting

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 9: Android Workshop 2013

About You

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 10: Android Workshop 2013

Todayrsquos Programme

8am - 10am Setting Up Android Studio

10am - 12pm Introduction to Android Programming

12pm - 1pm Lunch

1pm - 5pm 3 x hands-on (each 1 hr)

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 11: Android Workshop 2013

Objectives

Understand Android development process

Master Android Studio

Kickstart basic Android programming

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 12: Android Workshop 2013

Pre-requisite Java Programming

Java Programming Guidehttpmobiletutspluscomtutorialsandroidjava-tutorial

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 13: Android Workshop 2013

Introduction to Android

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 14: Android Workshop 2013

The Android OS

bull Linux Kernel

bull Write in Java code

bull Dalvik Virtual Machine

bull Application Framework

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 15: Android Workshop 2013

Android Architecture

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 16: Android Workshop 2013

Platform Versions

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 17: Android Workshop 2013

Development Process

Design

Develop

Distribute

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 18: Android Workshop 2013

Learn how to Design

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 19: Android Workshop 2013

bull PrinciplesGuidelines

bull UI Components

bull Common Patterns

Understanding Design

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 20: Android Workshop 2013

Design Principles

bull Simple

bull Looks the same act the same

bull Customizable

bull Icon style

bull Donrsquot mimic iPhone UI

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 21: Android Workshop 2013

UI Components

bull Buttons

bull Text Fields

bull Dialogs

bull Spinners

bull Action Bar

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 22: Android Workshop 2013

Button

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 23: Android Workshop 2013

Text Fields

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 24: Android Workshop 2013

Dialogs

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 25: Android Workshop 2013

Alerts

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 26: Android Workshop 2013

Spinner

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 27: Android Workshop 2013

Action Bar

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 28: Android Workshop 2013

Common Patterns

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 29: Android Workshop 2013

Change view on a set of data

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 30: Android Workshop 2013

Select multiple items

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 31: Android Workshop 2013

Dashboard

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 32: Android Workshop 2013

Devices amp Resolutions

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 33: Android Workshop 2013

dpi = dots per inch

for graphics

for fonts

dp = density independent pixels (1dp might be 1 pixel or 2 pixels depending on the dpi)

sp = scale independent pixels

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 34: Android Workshop 2013

App Icon

48x48 dp

48x48 px 72x72 px 96x96 px 144x144 px

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 35: Android Workshop 2013

Learn how to Code

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 36: Android Workshop 2013

AndroidManifestxml

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 37: Android Workshop 2013

4 Main Components

1 Activity

2 Service

3 Content Provider

4 Broadcast Receiver

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 38: Android Workshop 2013

Activity

bull Activity = Screen

bull An app is made up of 1 or more activities

bull Stack of activitiesscreens

bull Activity lifecycle

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 39: Android Workshop 2013

bull App-X can activate App-Y component

bull Intent

bull App-X can access App-Y shared data

bull Content Resolver

Activity

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 40: Android Workshop 2013

HelloWorldActivity

Activity class has functions to handle onCreate onResume onPause etc

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 41: Android Workshop 2013

Activity

bull Launch an Activity by calling startActivity(intent)

Launch a known ActivityIntent intent = new Intent(this SignInActivityclass)startActivity(intent)

Launch a system ActivityIntent intent = new Intent(IntentACTION_SEND)intentputExtra(IntentEXTRA_EMAIL recipientArray)startActivity(intent)

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 42: Android Workshop 2013

Activity

bull Activity must be declared in AndroidManifestxml

ltmanifest gt ltapplication gt ltactivity androidname=HelloWorldActivity gt ltapplication gt ltmanifest gt

HelloWorldActivity is shorthand for comjust2ushelloworldHelloWorldActivity

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 43: Android Workshop 2013

Service

bull Service runs in the background even when user is not interacting with your app

bull Service or Thread

bull To start call startService()

bull Similar to Activity has its lifecycle and various event callbacks

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 44: Android Workshop 2013

ContentProvider

bull A way to share data across applications including apps such as phonebook calendar etc

bull You can access the phonebook data using a ContentResolver

bull Have query insert delete methods (SQLite)

ContentResolver cr = getContentResolver()crquery(ldquocontentandroidproviderContactsPhonesCONTACT_URIrdquo

projectionselection selectionArgsortOrder)

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 45: Android Workshop 2013

BroadcastReceiver

bull Responds to system-wide broadcast announcements such as incoming phone call SMS sent picture captured etc

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 46: Android Workshop 2013

User Interfaces

Slides on httpwwwslidesharenetsamwize

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 47: Android Workshop 2013

View Hierarchy

1 View - Android UI component view or widget 2 ViewGroup - Layout or container view

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 48: Android Workshop 2013

View

bull UI components can be found in androidwidget package

bull Basic UI

bull TextView

bull Button

bull TextField

bull Progress bar

bull List

bull etc

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 49: Android Workshop 2013

ViewGroup(aka layout manager)

A simple LinearLayout

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 50: Android Workshop 2013

ViewGroup

TableLayout

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 51: Android Workshop 2013

ViewGroup

RelativeLayout

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 52: Android Workshop 2013

User Interfaces

bull 3 ways to construct UI

1 Drag-and-drop interface builder

2 XML

3 Code

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 53: Android Workshop 2013

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

looks in resvaluesstringxml and find the value for the key ldquohellordquo

Equivalently

androidtext=Hello world too

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 54: Android Workshop 2013

The way of XML

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid androidorientation=vertical androidlayout_width=fill_parent androidlayout_height=fill_parent gt ltTextView androidlayout_width=fill_parent androidlayout_height=wrap_content androidtext=stringhello gtltLinearLayoutgt

reslayoutmainxml

Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

setContentView() inflate mainxml and set the views

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 55: Android Workshop 2013

The way of Code

package comjust2ushelloandroid

import androidappActivityimport androidosBundleimport androidwidgetTextView

public class HelloAndroid extends Activity Called when the activity is first created Override public void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) TextView textview = new TextView(this) textviewsetText(Hello Android) setContentView(textview)

Creating a TextView and set the text

Similarly to the way of XML setContentView()

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 56: Android Workshop 2013

Preferences

bull The easiest way to store information

bull NOT only store preferencessettings but also arbitrary key-value pairs

bull SharedPreference class

bull getBoolean setBoolean etc

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 57: Android Workshop 2013

public class Calc extends Activity public static final String PREFS_NAME = MyPrefsFile

Override protected void onCreate(Bundle state) superonCreate(state)

Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) boolean silent = settingsgetBoolean(silentMode false) setSilent(silent)

Override protected void onStop() superonStop()

We need an Editor object to make preference changes All objects are from androidcontextContext SharedPreferences settings = getSharedPreferences(PREFS_NAME 0) SharedPreferencesEditor editor = settingsedit() editorputBoolean(silentMode mSilentMode)

Commit the edits editorcommit()

Preferences

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 58: Android Workshop 2013

Network

bull Connect to web services over HTTP

bull Permission needed in Manifestltuses-permission androidname=androidpermissionINTERNET gt

bull A few different ways to connect

bull HttpClient is most robust

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 59: Android Workshop 2013

Network - GET

HttpClient client = new DefaultHttpClient()HttpGet request = new HttpGet(httpwwwmyservercomscript1php)

Execute HTTP GET request and get responseHttpResponse response = clientexecute(request)InputStream is = responsegetEntity()getContent()BufferedReader in = new BufferedReader(new InputStreamReader(is)) Do what you need with content StringBuffer sb = new StringBuffer()String line = String NL = SystemgetProperty(lineseparator)while ((line = inreadLine()) = null)

sbappend(line + NL)inclose()String content = sbtoString()

Do what you need with content

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 60: Android Workshop 2013

Network - POST

HttpClient client = new DefaultHttpClient()HttpPost request = new HttpPost(httpwwwmyservercomlogin_scriptphp)

Add your dataListltNameValuePairgt nameValuePairs = new ArrayListltNameValuePairgt(2)nameValuePairsadd(new BasicNameValuePair(username samwize))nameValuePairsadd(new BasicNameValuePair(password 123456))requestsetEntity(new UrlEncodedFormEntity(nameValuePairs))

Execute HTTP POST RequestHttpResponse response = httpclientexecute(request)

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 61: Android Workshop 2013

Multimedia

bull Camera

bull Playback audio and video

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 62: Android Workshop 2013

Multimedia - Camera

bull 2 ways to capture photo

bull Using capture intent

bull Using Camera class directly

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 63: Android Workshop 2013

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStoreACTION_IMAGE_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE) create a file to save the image intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

start the image capture Intent startActivityForResult(intent CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)

Capture photo

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 64: Android Workshop 2013

Multimedia - Camera

private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200private Uri fileUri

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState) setContentView(Rlayoutmain)

create new Intent Intent intent = new Intent(MediaStoreACTION_VIDEO_CAPTURE)

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO) create a file to save the video intentputExtra(MediaStoreEXTRA_OUTPUT fileUri) set the image file name

intentputExtra(MediaStoreEXTRA_VIDEO_QUALITY 1) set the video image quality to high

start the Video Capture Intent startActivityForResult(intent CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE)

Capture video

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 65: Android Workshop 2013

Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200

Overrideprotected void onActivityResult(int requestCode int resultCode Intent data) if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Image captured and saved to fileUri specified in the Intent ToastmakeText(this Image saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the image capture else Image capture failed advise user

if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) if (resultCode == RESULT_OK) Video captured and saved to fileUri specified in the Intent ToastmakeText(this Video saved ton + datagetData() ToastLENGTH_LONG)show() else if (resultCode == RESULT_CANCELED) User cancelled the video capture else Video capture failed advise user

Handling after photovideo is captured by camera app

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 66: Android Workshop 2013

Multimedia - MediaPlayer

bull Play audio and video from

bull resraw

bull File system (internal or external)

bull Stream over Internet

bull MediaPlayer class

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 67: Android Workshop 2013

Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)mediaPlayerstart()mediaPlayerstop()

Playing resrawsound_file_1mp3

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 68: Android Workshop 2013

1 Hello World [60 min]

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 69: Android Workshop 2013

Objectives

bull Create new project

bull Understand project structure

bull Navigate in Android Studio

bull Run amp Debug

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 70: Android Workshop 2013

Demo

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 71: Android Workshop 2013

Project Structure

Java Code

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 72: Android Workshop 2013

Project Structure

Resources

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 73: Android Workshop 2013

The steps in brief

bull Create new project

bull Change App name

bull Run

bull View logs

bull Debug

Refer to hand-out 1 notes

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 74: Android Workshop 2013

2 Stopwatch [60 min]

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 75: Android Workshop 2013

Objectives

bull Create widgets in design mode

bull Edit widgets in XML text mode

bull Code how stopwatch works

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 76: Android Workshop 2013

Demo

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 77: Android Workshop 2013

The steps in brief

bull Create 2 buttons

bull Edit the names and id

bull Code the stopwatch logic

Refer to hand-out 2 notes

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 78: Android Workshop 2013

3 Polish Stopwatch [60 min]

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 79: Android Workshop 2013

Objectives

bull Create Responsive Layout

bull Style the UI

bull Enhance UX

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 80: Android Workshop 2013

Demo

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 81: Android Workshop 2013

The steps in brief

bull Edit layout

bull Add background image

bull Custom font

bull Button with background image

bull Button with states

Refer to hand-out 3 notes

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 82: Android Workshop 2013

Whatrsquos Next

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 83: Android Workshop 2013

Database

bull Tabular data

bull SQLite behind the scenes

bull Extend SQLiteOpenHelper

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 84: Android Workshop 2013

Database

public class DictionaryOpenHelper extends SQLiteOpenHelper

private static final int DATABASE_VERSION = 2 private static final String DICTIONARY_TABLE_NAME = dictionary private static final String DICTIONARY_TABLE_CREATE = CREATE TABLE + DICTIONARY_TABLE_NAME + ( + KEY_WORD + TEXT + KEY_DEFINITION + TEXT)

DictionaryOpenHelper(Context context) super(context DATABASE_NAME null DATABASE_VERSION)

Override public void onCreate(SQLiteDatabase db) dbexecSQL(DICTIONARY_TABLE_CREATE)

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 85: Android Workshop 2013

Database

bull Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object

bull With SQLiteDatabase call query() to execute SQL queries

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 86: Android Workshop 2013

More Topics

bull Location (GPS) and Map

bull Bluetooth

bull USB host and accessory

bull Animation

bull OpenGL ES

bull Push Messaging (GCM)

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 87: Android Workshop 2013

Arduino amp Bluetooth

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom

Page 88: Android Workshop 2013

Important Resources

bull httpdeveloperandroidcom

bull httpstackoverflowcom

bull httpwwwgooglecom