99
Course Overview Android Developers Website http://developer.android.com/guide/components/index.html Google Play is a trademark of Google Inc. Portions of this page are reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

04 App Components and APIs

  • Upload
    aditux

  • View
    229

  • Download
    0

Embed Size (px)

DESCRIPTION

04 App Components and APIs Android Studio

Citation preview

Page 1: 04 App Components and APIs

C o u rs e O ve r v i e w

A n d r o i d D e v e l o p e r s W e b s i t e

http://developer.android.com/guide/components/index.html

Google Play is a trademark of Google Inc.

Portions of this page are reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Page 2: 04 App Components and APIs

A p p C o m p o n e n t s a n d A P I s

http://developer.android.com

/guide/components/index.html

The basic

building blocks

of app actions.

Portions of this page are reproduced

from work created and shared by the

Android Open Source Project and used

according to terms described in

the Creative Commons 2.5 Attribution

License.

Page 3: 04 App Components and APIs

A p p C o m p o n e n t s a n d A P I s i n U s e

Components • Activities

• Content Providers

• Services

• Broadcast Receivers

Resources • XML

• Images

Eclipse/

Android Tools

APK

Android

Package

- Fragments

- Widgets

- Processes & Threads

- Messaging

- Memory Management

- Permissions

APIs • Classes

• Methods

Google

Play

Android

Application

APK

Creation

APK

Download

APK

Upload

App

Development

Device

Supplier

Load

Android OS Multi-user Linux System

By Smieh (This file was derived from:

Sample.svg) [CC-BY-SA-3.0

(http://creativecommons.org/licenses/by-

sa/3.0)], via Wikimedia Commons

Page 4: 04 App Components and APIs

http://en.wikipedia.org/wiki/Android_

(operating_system)#Development

A n d ro i d A rc h i t e c t u re

http://developer.android.com/guide

/components/fundamentals.html

Each app is

a separate

Linux user

with its own

Linux user ID

(unknown to

the app).

Each app

process has

its own

Dalvik Virtual

Machine,

which runs in

its own Linux

process.

Multi-user Linux System

Permissions

are set for

all files in an

app so that

only the

user ID

assigned to

that app can

access

them.

By Smieh (This

file was derived

from:

Sample.svg)

[CC-BY-SA-3.0

(http://creativeco

mmons.org/licen

ses/by-sa/3.0)],

via Wikimedia

Commons

Page 5: 04 App Components and APIs

A n d ro i d L i n u x

Process • Scheduling

• Time Sharing

• Prioritization

• Code Execution

Linux is a branch of the Unix operating system:

Some Android changes to the Linux Kernel:

http://elinux.org/Android_Kernel_Features

http://en.wikipedia.org/wiki/File:Unix_history.svg

Linux is open source and was

initially developed in the 1990’s: http://en.wikipedia.org/wiki/Linux

http://oreilly.com/catalog/linuxkernel/chapter/ch10.html

By Smieh (This file was

derived from: Sample.svg)

[CC-BY-SA-3.0

(http://creativecommons.org/lic

enses/by-sa/3.0)], via

Wikimedia Commons

Page 6: 04 App Components and APIs

A p p L i fe c yc l e s

- Activities

- Services

- Content Providers

- Broadcast Receivers

onPhase1() { . . . }

onPhase2() { . . . }

onPhase3() { . . . }

.

.

L i f e c y c l e P h a s e s

Lifecycle Patterns Lifecycle Methods

By Smieh (This file was derived from: Sample.svg) [CC-BY-SA-3.0

(http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

Process

Page 7: 04 App Components and APIs

A p p T h re a d s Main/UI Thread

Non-User Interface Actions

Background/Worker Thread

Data By Smieh (This file was

derived from:

Sample.svg) [CC-BY-

SA-3.0

(http://creativecommons.

org/licenses/by-sa/3.0)],

via Wikimedia Commons

Process

Page 8: 04 App Components and APIs

A p p C o m p o n e n t s a n d A P I s

http://developer.android.com

/guide/components/index.html

The basic

building blocks

of app actions.

Portions of this page are reproduced

from work created and shared by the

Android Open Source Project and used

according to terms described in

the Creative Commons 2.5 Attribution

License.

Page 9: 04 App Components and APIs

Activities Content

Providers

Services Broadcast Receivers

A c t i v i t i e s

Page 10: 04 App Components and APIs

A c t i v i t i e s A P I

http://developer.android.com

/guide/components/activities.html

Development API Guide

Basic Description

Detailed Description

Overview

Page 11: 04 App Components and APIs

F i rs t A p p A c t i v i t y

L i f e c y c l e P h a s e s

Extends

Activity

Class

A c t i v i t y M e t h o d s

Page 12: 04 App Components and APIs

A c t i v i t y C l a s s

http://developer.android.com

/reference/android/app/Activity.html

Hierarchy of Class Extensions

Development Reference

“An activity is a single, focused

thing that the user can do.”

Summary Links

Subclasses

Class Overview

Page 13: 04 App Components and APIs

A c t i v i t y L i fe c yc l e

Running Not Visible Shut Down

onStart() onPause() onStop() onCreate() onResume()

onRestart()

onDestroy()

Partially Visible Launch

Page 14: 04 App Components and APIs

A c t i v i t y L i fe c yc l e

Portions of this page are

reproduced from work created

and shared by the Android Open

Source Project and used

according to terms described in

the Creative Commons 2.5

Attribution License.

Page 15: 04 App Components and APIs

A c t i v i t y L i fe c yc l e M e t h o d s a n d Ty p i c a l U s e s

onStart() • Register Broadcast

Receiver

• Reinitialize states

onResume() • Restore variables

• Restart animations

• Lightweight code

onCreate() • Must be implemented

• Call setContentView()

• Initialize display layout

• Initialize variables

• Start background thread

onPause() • Commit changes

• Save variables

• Save preferences

• Stop animations

• Lightweight code

onStop() • Close server

connections

• Free resources

• Unregister

Broadcast

Receiver onDestroy() • Close databases

• Release remaining

resources

• Stop background thread

onRestart() • Open server

connections

• Allocate

resources

Portions of this page are

reproduced from work created

and shared by the Android Open

Source Project and used

according to terms described in

the Creative Commons 2.5

Attribution License.

http://developer.android.com/guide/components

/activities.html#ImplementingLifecycleCallbacks

Implementing Lifecycle Callbacks

Page 16: 04 App Components and APIs

S av i n g A c t i v i t y S t a t e

http://developer.android.com/guide

/components/activities.html#SavingActivityState

Portions of this page are

reproduced from work created

and shared by the Android Open

Source Project and used

according to terms described in

the Creative Commons 2.5

Attribution License.

Page 17: 04 App Components and APIs

U n d e rs t a n d i n g a n A P I

Familiarity with major aspects

Understand key and

required capabilities

Research as needed

Portions of this page are reproduced from work created

and shared by the Android Open Source Project and used

according to terms described in the Creative Commons 2.5

Attribution License.

Page 18: 04 App Components and APIs

Activities Content

Providers

Services Broadcast Receivers

A c t i v i t i e s

Page 19: 04 App Components and APIs

C re a t i n g a P ro j e c t f ro m E x i s t i n g C o d e

Including a detailed look

“under the hood.”

Code Refactoring

Page 20: 04 App Components and APIs

O p e n i n g Yo u r Wo r k s p a c e

Page 21: 04 App Components and APIs

S e l e c t i n g t h e P ro j e c t f ro m E x i s t i n g C o d e W i za rd

Page 22: 04 App Components and APIs

S e l e c t i n g t h e P ro j e c t t o I m p o r t

Check

Select

First

App

Project

Select

Workspace

Uses

activity

name as

app name

Page 23: 04 App Components and APIs

Re n a m i n g A p p P ro j e c t a n d Pa c ka ge

Rename Project to AddActivityExample

Rename Package to

com.donkcowan.addactivityexample

Actual folder structure

under src and gen:

com

donkcowan

firstappproject Verify changes in Manifest

Change app_name in string values

You can use your own name or any

other name you choose for the middle

qualifier – or leave it as donkcowan for

now. When you publish apps to

Google Play, you’ll need a unique

qualifier, usually a domain name which

assures uniqueness.

Page 24: 04 App Components and APIs

Re n a m i n g t h e P ro j e c t

Change to AddActivityExample

Page 25: 04 App Components and APIs

Re n a m i n g t h e A p p l i c a t i o n Pa c ka ge

Change to addactivityexample

Page 26: 04 App Components and APIs

C h a n ge Ve r i f i c a t i o n

Gives you an opportunity

to preview the changes

that will be made to your

application.

Page 27: 04 App Components and APIs

A d d e d I m p o r t S t a t e m e n t

An import statement may

be added to your Java

source for the .R file.

Once you’ve done all your

renaming you won’t need

this, but it does no harm

to include it.

Page 28: 04 App Components and APIs

U p d a t i n g t h e L a u n c h C o n f i g u ra t i o n

Page 29: 04 App Components and APIs

L a u n c h C o n f i g u ra t i o n M a n a ge m e n t

Page 30: 04 App Components and APIs

Re n a m i n g t h e S rc Pa c ka ge N a m e

Change to addactivityexample

Page 31: 04 App Components and APIs

Pa c ka ge A l re a d y E x i s t s

Because you’ve already

made changes using the

addactivityexample

package name, this

warning appears. Just

ignore it and click

continue.

Page 32: 04 App Components and APIs

P re v i e w o f C h a n ge s

Gives you an opportunity to

preview the changes that will be

made to your application.

Page 33: 04 App Components and APIs

C h a n g i n g t h e A p p N a m e S t r i n g

Change to Add Activity Example

Page 34: 04 App Components and APIs

C h a n ge s i n t h e M a n i fe s t

Changed to

addactivityexample

Package name of

com.donkcowan.addactivityexample

removed but will be assumed.

Can add it back in if you like.

Page 35: 04 App Components and APIs

C re a t i n g a P ro j e c t f ro m E x i s t i n g C o d e

Page 36: 04 App Components and APIs

A d d i n g a n A c t i v i t y t o a n E x i s t i n g P ro j e c t

Page 37: 04 App Components and APIs

O p e n i n g Yo u r Wo r k s p a c e

Page 38: 04 App Components and APIs

S e l e c t i n g t h e A c t i v i t y W i za rd

Page 39: 04 App Components and APIs

N a m i n g a N e w A c t i v i t y

Don’t check

Select None

Page 40: 04 App Components and APIs

N e w A c t i v i t y F i l e A d d i t i o n s

Source

Layout

Menu

If source is placed in a

different project folder,

move it to the

addactivityexample

folder.

Page 41: 04 App Components and APIs

N e w A c t i v i t y M a n i fe s t C o d e

Page 42: 04 App Components and APIs

A d d i n g a n A c t i v i t y t o a n E x i s t i n g P ro j e c t

Page 44: 04 App Components and APIs

F i rs t A p p M a n i fe s t

Package Name

Component (Activity)

SDK Levels

Version IDs

Application Attributes

Intent Filters

Names defined in resources

Package Name

Version IDs

SDK Levels

App Attributes

Components

Intent Filters - - -

Page 45: 04 App Components and APIs

M a n i fe s t U s e s

Filter

Pass

Fail

Configuration

App/

Intents

Package Name

Version IDs

SDK Levels

App Attributes

Components

Permissions

Uses Specifications

Lifecycle

Intent Filters

- - - - - - - - - -

- - - - - - - - - -

- - - - - - - - - -

Implicit Intent

Start

Action Tests

Category Tests

Data Tests

Explicit Intent Component

Intent Typing

Page 46: 04 App Components and APIs

I n t e n t F i l t e r S t a n d a rd A c t i o n s

Standard Broadcast Actions (were performed)

ACTION_TIME_TICK

ACTION_TIME_CHANGED

ACTION_TIMEZONE_CHANGED

ACTION_BOOT_COMPLETED

ACTION_PACKAGE_ADDED

ACTION_PACKAGE_CHANGED

ACTION_PACKAGE_REMOVED

ACTION_PACKAGE_RESTARTED

ACTION_PACKAGE_DATA_CLEARED

ACTION_UID_REMOVED

ACTION_BATTERY_CHANGED

ACTION_POWER_CONNECTED

ACTION_POWER_DISCONNECTED

ACTION_SHUTDOWN

Most important and

frequently used

ACTION_MAIN

ACTION_VIEW

ACTION_ATTACH_DATA

ACTION_EDIT

ACTION_PICK

ACTION_CHOOSER

ACTION_GET_CONTENT

ACTION_DIAL

ACTION_CALL

ACTION_SEND

ACTION_SENDTO

ACTION_ANSWER

ACTION_INSERT

ACTION_DELETE

ACTION_RUN

ACTION_SYNC

ACTION_PICK_ACTIVITY

ACTION_SEARCH

ACTION_WEB_SEARCH

ACTION_FACTORY_TEST

Standard Activity Actions (to be performed)

Start up component as the

initial activity of a task.

Display data for the user to edit.

First App:

Page 47: 04 App Components and APIs

I n t e n t F i l t e r S t a n d a rd C a t e g o r i e s

CATEGORY_DEFAULT

CATEGORY_BROWSABLE

CATEGORY_TAB

CATEGORY_ALTERNATIVE

CATEGORY_SELECTED_ALTERNATIVE

CATEGORY_LAUNCHER

CATEGORY_INFO

CATEGORY_HOME

CATEGORY_PREFERENCE

CATEGORY_TEST

CATEGORY_CAR_DOCK

CATEGORY_DESK_DOCK

CATEGORY_LE_DESK_DOCK

CATEGORY_HE_DESK_DOCK

CATEGORY_CAR_MODE

CATEGORY_APP_MARKET

The activity can be the initial

activity of a task and is listed in

the top-level application

launcher.

First App:

Page 48: 04 App Components and APIs

M a n i fe s t X M L Ta g s

<permission>

<permission-group>

<permission-tree>

<provider>

<receiver>

<service>

<supports-screens>

<uses-configuration>

<uses-feature>

<uses-library>

<uses-permission>

<uses-sdk>

http://developer.android.com/guide/topics/manifest/manifest-intro.html#filestruct

<action>

<activity>

<activity-alias>

<application>

<category>

<data>

<grant-uri-permission>

<instrumentation>

<intent-filter>

<manifest>

<meta-data>

Page 50: 04 App Components and APIs

I n t e n t Ty p i n g a n d F i l t e r i n g

Filter

Pass

Fail

Configuration

App/

Intents

Package Name

Version IDs

SDK Levels

App Attributes

Components

Permissions

Uses Specifications

Lifecycle

Intent Filters

- - - - - - - - - -

- - - - - - - - - -

- - - - - - - - - -

Implicit Intent

Start

Action Tests

Category Tests

Data Tests

Explicit Intent Component

Intent Typing

Page 51: 04 App Components and APIs

P r i m a r y I n t e nt I n fo r m a t i o n

action -- The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.

data -- The data to operate on, such as a person record in the contacts database, expressed as a Uri, such as http://www.google.com

Examples

action data ACTION_VIEW content://contacts/people/1 -- Display information about the person whose identifier is "1".

ACTION_DIAL content://contacts/people/1 -- Display the phone dialer with the person filled in.

ACTION_DIAL tel:123 -- Display the phone dialer with the given number filled in.

ACTION_EDIT content://contacts/people/1 -- Edit information about the person whose identifier is "1".

ACTION_VIEW content://contacts/people/ -- Display a list of people, which the user can browse through.

Page 52: 04 App Components and APIs

O t h e r I n t e n t I n fo r m a t i o n

In addition to these primary attributes, there are a number of secondary attributes that you can also include with an intent:

category -- Gives additional information about the action to execute. For example, CATEGORY_LAUNCHER means it

should appear in the Launcher as a top-level application, while CATEGORY_ALTERNATIVE means it should be included in

a list of alternative actions the user can perform on a piece of data.

type -- Specifies an explicit type (a MIME type) of the intent data. Normally the type is inferred from the data itself. By

setting this attribute, you disable that evaluation and force an explicit type.

component -- Specifies an explicit name of a component class to use for the intent. Normally this is determined by looking

at the other information in the intent (the action, data/type, and categories) and matching that with a component that can

handle it. If this attribute is set then none of the evaluation is performed, and this component is used exactly as is. By

specifying this attribute, all of the other Intent attributes become optional.

extras -- This is a Bundle of any additional information. This can be used to provide extended information to the

component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to

supply a subject, body, etc.

http://developer.android.com/reference/android/content/Intent.html For more information see:

Page 53: 04 App Components and APIs

C re a t i n g a N e w P ro j e c t t o D e m o n st ra t e I n t e n t s

Page 54: 04 App Components and APIs

E x p l i c i t I n t e n t E xa m p l e

Page 55: 04 App Components and APIs

E x p l i c i t I n t e n t fo r A c t i v i t y

S t a r t

name of intent object

class indication

Name of component class

Declares object as an intent

new instance of object

Intent class

startActivity method

Intent for activity to be started method signature to create an

intent for a specific component

context of this activity

Page 56: 04 App Components and APIs

I m p l i c i t I n t e n t E xa m p l e

Page 57: 04 App Components and APIs

I m p l i c i t I n t e n t fo r B ro w s e r

D i s p l ay

name of intent object

Scheme part

Scheme name

parse method

Uri class

Declares object as an intent

new instance of object

Intent object

Intent class

startActivity method

Intent for activity to be started method signature to create an intent with

a given action with a specific data url

Action View string

Page 58: 04 App Components and APIs

H o w I n t e n t s w e re u s e d i n O u r E xa m p l e

Intents

Example

Page 59: 04 App Components and APIs

L i s t e n e r fo r B u tt o n

C l i c k

name of button object

Listener object

id of button

declares object as a button

casting as a button

find view of button in layout

declares OnClickListener object new instance of object

Set listener on button object

onClick method OnClickListener object

Standard sequence of

statements used for

setting up listeners for

user interaction with

screen objects. View object parameter

. . .

call back code

Page 60: 04 App Components and APIs

D i s p l ay To a st

Toast class constant

name of context object

declares object as a Context

getApplicationContext method

show method to display toast

Toast object name

Declaration

of Toast

object

makeText

method of

Toast class name of context object

duration

variable

Text variable

(defined

elsewhere)

duration

variable

Page 61: 04 App Components and APIs

L i s t e n e rs a n d To a st s Set up listener for button click Respond to click listener Set up display Accept input Toast answer

Page 62: 04 App Components and APIs

A p p T h re a d s Main/UI Thread

Non-User Interface Actions

Background/Worker Thread

Data By Smieh (This file was

derived from:

Sample.svg) [CC-BY-

SA-3.0

(http://creativecommons.

org/licenses/by-sa/3.0)],

via Wikimedia Commons

Process

Page 63: 04 App Components and APIs

Ba

ck

gro

un

d T

as

k

Ex

am

ple

onCreate() Main

Thread

AsyncTask

Background

Thread

onClickListener()

publishProgress() onPostExecute()

onProgressUpdate()

onPreExecute() doInBackground()

execute()

Page 65: 04 App Components and APIs

S e r v i c e s

Activities Content

Providers

Services Broadcast Receivers

Portions of this page are reproduced from work created

and shared by the Android Open Source Project and

used according to terms described in the Creative

Commons 2.5 Attribution License.

http://developer.android.com/guide

/components/services.html

Page 66: 04 App Components and APIs

Thread

O b j e c t s U s e d t o I m p l e m e n t a S e r v i c e

Handler/Looper Provides the capability to run multiple tasks on a single thread Handler ServiceHandler HandlerThread Looper getLooper() obtainMessage() sendMessage() start() stopSelf() handleMessage()

MessageQueue List of messages to be dispatched by a Looper

Message Contains descriptions, arguments and objects being sent

Thread Concurrent unit of execution with its own stack of methods with their arguments and variables

Process

Main classes and

methods for executing

a service

Service

Execution

Service

Interface

Process

Intent (Explicit) startService() stopService() App Specific

Service Tasks Code to carry out tasks specific to the application

Service

OnClickListener onClick()

Activity

Button findViewById()

Activity setContentView()

Page 67: 04 App Components and APIs

Serv

ice

Exam

ple

onCreate()

Service

Interface

(Activity)

Service

Execution

(Service) onStartCommand() onDestroy() handleMessage() onBind() serviceHandler() onCreate()

onClickListener() startService()

onClickListener() stopService()

Thre

ad

Thre

ad

Page 68: 04 App Components and APIs

No

tePa

d A

pp

C

on

ten

t P

rovi

der

onCreate()

Content

User

Content

Manager

(Thre

ad)

Thre

ad

query() insert() update()

delete() getType() onCreate()

Content Provider

SQLiteDatabase SQLiteQueryBuilder SQLiteOpenHelper

Database Management

getListView() setListAdapter() onListItemClick()

List Display and Handling

onCreateOptionsMenu() onPrepareOptionsMenu() onOptionsItemSelected()

Menu Display and Handling

EditText findViewById()

query() insert() update()

delete() getType()

Content Interface Editing

ContentResolver Uri Cursor ContentValues

Data Subset

Database

Page 69: 04 App Components and APIs

C o n t e n t P ro v i d e rs

Activities Content

Providers

Services Broadcast Receivers

Portions of this page are reproduced from work created

and shared by the Android Open Source Project and

used according to terms described in the Creative

Commons 2.5 Attribution License.

Use when your app needs to: • Share data with other apps

• Provide custom search

suggestions

• Copy and paste complex data

or files from your app to other

apps

http://developer.android.com/guide/topics

/providers/content-providers.html

http://developer.android.com/guide

/topics/search

/adding-custom-suggestions.html

http://developer.android.com/guide

/topics/text/copy-paste.html

Custom Search

Copy and Paste

Page 70: 04 App Components and APIs

C o n t e n t P ro v i d e r C l a s s e s a n d O b j e c t s

ContentProvider

Manages Provider and Data Access.

Main methods are:

query() update() insert() delete() getType() onCreate() Uses and supplements parameters from Content Interface to execute DB Management methods .

Provides return values to Content Interface.

Handles return values from Database Management.

Content Interface

Manages access to ContentProvider and exchange of data with User Interface.

Main methods used are:

query() update() insert() delete() getType() Creates parameters for the methods from User Interface variables. Handles return values from ContentProvider.

Database

Database

Management

User

Displays

and

Inputs

User

Interface

Uri

Cursor

ContentValues

Data Access

ContentResolver Provides access to the data subset.

Main methods are:

query() update() insert() delete() getType()

File

File

Management

Provider Access

Data Subset

Page 71: 04 App Components and APIs

D a t a S p e c i f i c a t i o n

Column 0 Row 0

Value

Column

Cursor

ContentValues Uri

query()

insert()

update()

delete()

getType() Database

Query

Result Set

Page 72: 04 App Components and APIs

U R I ( U n i fo r m Re s o u rc e I d e n t i f i e r )

Column 0 Row 0

Value

Column

Cursor

ContentValues Uri

Database

Query

Result Set

query()

insert()

update()

delete()

getType()

Page 73: 04 App Components and APIs

U R I Fo r m a t

scheme:scheme-specific-part

Examples: Web address http://example.org/absolute/URI/with/absolute/path/to/resource.txt File transfer ftp://example.org/resource.txt Resource name urn:isbn:0-486-27557-4 Android content provider content://com.google.provider.NotePad/notes/4

http://en.wikipedia.org/wiki/Uniform_resource_identifier

http://en.wikipedia.org/wiki/URI_scheme

Page 74: 04 App Components and APIs

C o n t e n t P ro v i d e r U R I

// Define URI component strings. String SCHEME = ContentResolver.SCHEME.CONTENT; // Scheme (content://) String AUTHORITY = "com.google.provider.NotePad"; // Authority for controlling access String PATH_NOTE_ID = “/notes"; // Path to identify an individual group String SAMPLE_Id = “/4"; // ID to specify a single row number // Defines a URI in the required format. // In this example the resulting string is “content://com.google.provider.NotePad/notes/4” Uri SAMPLE_URI = Uri.parse( // Use parse() method to format a Uri SCHEME + // Scheme AUTHORITY + // Authority PATH_NOTE_ID + // Path – none, one or multiple paths SAMPLE_ID); // ID - optional

Used for methods: query()

insert()

update()

delete()

getType()

Identifies a data subset

content://authority/path/id

Page 75: 04 App Components and APIs

U R I M a t c h e r

addURI(String authority, String path, int code)

- authority controls access to data - path identifies individual elements

* used to match any character # used to match number

- code is the number returned on a match

// Add entries to UriMatcher: // authority path code // ----------------- -------- ------- sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES ); sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID);

match(Uri uri) returns int code

- uri controls access to data - code is the number returned on a match

UriMatcher(int code)

- code to match for the root URI // Create a new instance of UriMatcher object // NO_MATCH = -1 for no matched nodes private static final UriMatcher sUriMatcher; sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

Description Example

// Use match() method to retrieve code for the uri switch (sUriMatcher.match(uri)) { // Take action based on code case NOTES: qb.setProjectionMap(sNotesProjectionMap); break; case NOTE_ID: qb.setProjectionMap(sNotesProjectionMap); . . .

Create

Setup

Switch

Steps

Page 76: 04 App Components and APIs

C u rs o r U s e i n C o n t e n t P ro v i d e rs

Column 0 Row 0

Cursor

Uri

Database

Query

Result Set

query()

Page 77: 04 App Components and APIs

C o n t e n t P ro v i d e r C l a s s e s a n d O b j e c t s

ContentProvider

Manages Provider and Data Access.

Main methods are:

query() update() insert() delete() getType() onCreate() Uses and supplements parameters from Content Interface to execute DB Management methods .

Provides return values to Content Interface.

Handles return values from Database Management.

Content Interface

Manages access to ContentProvider and exchange of data with User Interface.

Main methods used are:

query() update() insert() delete() getType() Creates parameters for the methods from User Interface variables. Handles return values from ContentProvider.

Database

Database

Management

User

Displays

and

Inputs

User

Interface

Uri

Cursor

ContentValues

Data Access

ContentResolver Provides access to the data subset.

Main methods are:

query() update() insert() delete() getType()

File

File

Management

Provider Access

Data Subset

Page 78: 04 App Components and APIs

C u rs o r C l a s s a n d O b j e c t s

Used for methods: query()

Column 0 Row 0

move(int offset)

moveToFirst()

moveToLast()

moveToNext()

moveToPrevious()

moveToPosition(int position)

getDouble(int columnIndex)

getFloat(int columnIndex)

getLong(int columnIndex)

getShort(int columnIndex)

getString(int columnIndex)

getDouble(int columnIndex)

columnIndex

getColumnIntdex(String columnName)

getColumnCount()

getColumnNames()

getCount() (returns total number of rows)

setNotificationUri(ContentResolver cr, Uri uri)

Result

Set

Keeps

track of

current

row

number

Cursor c (return from a query)

Provide read/write

access to a result

set returned from a

database query. Cursor is used by

other classes and

methods such as

cursor adapters for

list displays.

Page 79: 04 App Components and APIs

C o n t e n t P ro v i d e r M e t h o d s ContentProvider

Manages Provider and Data Access.

Main methods are:

query() update() insert() delete() getType() onCreate() Uses and supplements parameters from Content Interface to execute DB Management methods .

Provides return values to Content Interface.

Handles return values from Database Management.

Content Interface

Manages access to ContentProvider and exchange of data with User Interface.

Main methods used are:

query() update() insert() delete() getType() Creates parameters for the methods from User Interface variables. Handles return values from ContentProvider.

Database

Database

Management

User

Displays

and

Inputs

User

Interface

Uri

Cursor

ContentValues

Data Access

ContentResolver Provides access to the data subset.

Main methods are:

query() update() insert() delete() getType()

File

File

Management

Provider Access

Data Subset

Page 80: 04 App Components and APIs

o n C re a t e ( ) M e t h o d

ContentResolver tries to access ContentProvider for first time

ContentProvider object created

ContentProvider onCreate method invoked

ContentProvider onCreate() method

• Initialize variables • Open files/database • Keep minimal

Content Interface uses a ContentResolver object to access some data for the first time

Page 81: 04 App Components and APIs

Ke y M e t h o d s Parameters query() insert() update() delete() getType()

Uri

Projection

Selection Clause

Selection Arguments

Sort Order

ContentValues

Cancellation Signal (Introduced in API 16)

Cursor Uri int number of rows affected

int number of rows affected

String of MIME type

Parameter Use

Return Use

User

Displays

User

Interface

Database

Database

Management

Applicable

Can be null

Page 82: 04 App Components and APIs

C o n t e n t Va l u e s

// Defines an object to contain new values to insert. ContentValues mValues = new ContentValues(); // Sets values in the ContentValues object // using the put() method of the ContentValues class // with Column Name and Value string as parameters. // // Key (Column Name) Value // ------------------------------- ------- mValues.put( NotePad.Notes.COLUMN_NAME_TITLE, "Milk“ ); // Sets title Milk mValues.put( NotePad.Notes.COLUMN_NAME_TYPE, "Soy“ ); // Sets type Soy

Used for methods: insert()

update()

Identifies column/value pairs

Column 0 Row 0

Milk Soy

title type

Page 83: 04 App Components and APIs

S e l e c t i o n C l a u s e a n d A rg u m e n t s

// Defines the criteria for which rows to return, // formatted as an SQL WHERE clause (excluding the WHERE itself). // Passing null will return all rows for the given table. // Question marks will be replaced with corresponding entry in the // selection arguments parameter below. String mSelectionClause = // Define a string "NotePad.Notes.COLUMN_NAME_TITLE=? AND // Title column selection NotePad.Notes.COLUMN_NAME_TYPE=?"; // Type column selection // Defines values input by user to be paired // with selection clause fields above. String[] mSelectionArguments = new String[] { // Create a string array “Milk”, // Title input by user “Soy”}; // Type input by user

Used for methods: query()

update()

delete()

Identifies criteria for

access operations

Column 0 Row 0

title type

Milk Soy

Milk Soy

Page 84: 04 App Components and APIs

P ro j e c t i o n

// Defines the columns to be returned for each row returned from a query. String[] mProjection = new String[] { // Create a string array NotePad.Notes._ID, // Column = "_ID" NotePad.Notes.COLUMN_NAME_TITLE }; // Column = "title"

Used for methods: query()

Identifies columns for data retrieval

Column 0 Row 0

_ID title

Page 85: 04 App Components and APIs

S o r t O rd e r

// Specifies the column to be used to sort query results. String mSortOrder = "NotePad.Notes.COLUMN_NAME_TITLE" // Title column sort

Used for methods: query()

Identifies column for sort

Column 0 Row 0

title

Page 86: 04 App Components and APIs

C a n c e l l a t i o n S i g n a l Used for methods: query()

Cancels operation in progress

// Create a CancellationSignal object. // Introduced in API 16. // If this parameter is used, you must also implement // a query() method without it to support previous versions. CancellationSignal mCancellationSignal = new CancellationSignal() // Instantiate CancellationSignal . . . // Cancel the query operation. mCancellationSignal.cancel();

Page 87: 04 App Components and APIs

M I M E Ty p e Used for methods: getType()

http://en.wikipedia.org/wiki/Internet_media_type

http://www.iana.org/assignments/media-types

String in the format: type/subtype/optional-parameters

Types: application, audio, image, message, text, video, . . . Text subtype examples: calendar, plain, html, xml Example: “text/html”

Provides information about the file type

http://developer.android.com/guide/topics/providers/content-provider-basics.html#MIMETypeReference

Type for multiple rows: vnd.android.cursor.dir Type for Single row: vnd.android.cursor.item Subtype example: vnd.google.note Example: “vnd.android.cursor.dir/vnd.google.note”

Standard

Android

Vendor-

Specific

Custom

Page 88: 04 App Components and APIs

C o n t e n t P ro v i d e r M e t h o d s ContentProvider

Manages Provider and Data Access.

Main methods are:

query() update() insert() delete() getType() onCreate() Uses and supplements parameters from Content Interface to execute DB Management methods .

Provides return values to Content Interface.

Handles return values from Database Management.

Content Interface

Manages access to ContentProvider and exchange of data with User Interface.

Main methods used are:

query() update() insert() delete() getType() Creates parameters for the methods from User Interface variables. Handles return values from ContentProvider.

Database

Database

Management

User

Displays

and

Inputs

User

Interface

Uri

Cursor

ContentValues

Data Access

ContentResolver Provides access to the data subset.

Main methods are:

query() update() insert() delete() getType()

File

File

Management

Provider Access

Data Subset

Page 89: 04 App Components and APIs

C o nt e nt I n t e r fa c e a n d P ro v i d e r M e t h o d Te m p l a t e s Content Interface Template ContentProvider Template

Parameters Inputs

ContentResolver Method Execution

Parameters Pass-through

Method Override

Execute database operation Set Notification of change

Database

Database

Management

User

Displays

User

Interface

Used for methods: query()

insert()

update()

delete()

getType()

Return Variable Return Value

Page 90: 04 App Components and APIs

C o n t e n t I n t e r fa c e M e t h o d Te m p l a t e

// Define parameters needed for access. (see parameter specific graphics) . . . // Define a variable to hold return depending on the type of access. Use one of: Cursor mReturn = new Cursor(); // Define Cursor for query operation. Uri mReturn = new Uri(); // Define Uri for insert operation. int mReturn = 0; // Define int for update or delete operation. String mReturn = ""; // Define MIME type String for getType operation. // Execute operation and assign return result. // Replace access with one of query, insert, update, delete, getType method names. mReturn = getContentResolver().access( // Get Content Resolver and perform operation. mUri, // Parameter values - which are set by mProjection, // code executed prior to this statement. mSelectionClause, // Use parameters depending on access type. mSelectionArguments, // Some parameters can be null. mSortOrder, mValues, mCancellationSignal);

parameters

return

access

Use appropriate:

parameters

Page 91: 04 App Components and APIs

Ke y M e t h o d s Parameters query() insert() update() delete() getType()

Uri

Projection

Selection Clause

Selection Arguments

Sort Order

ContentValues

Cancellation Signal (Introduced in API 16)

Cursor Uri int number of rows affected

int number of rows affected

String of MIME type

Parameter Use

Return Use

User

Displays

User

Interface

Database

Database

Management

Applicable

Can be null

Page 92: 04 App Components and APIs

Ke y M e t h o d s Parameters query() insert() update() delete() getType()

Uri

Projection

Selection Clause

Selection Arguments

Sort Order

ContentValues

Cancellation Signal (Introduced in API 16)

Cursor Uri int number of rows affected

int number of rows affected

String of MIME type

Parameter Use

Return Use

User

Displays

User

Interface

Database

Database

Management

Applicable

Can be null

Page 93: 04 App Components and APIs

C o n t e n t P ro v i d e r M e t h o d Te m p l a t e

// Use UriMatcher to take actions based on the Uri. (see Uri Matcher graphic) . . . // Execute operation and return result. // Replace return with one of Cursor, Uri, int, String return types. // Replace access with one of query, insert, update, delete, getType method names. @Override // Override to sync with Content Interface public return access( // Declare method with result Uri uri, // These are the parameters passed through String[] projection, // from the Content Interface use String selectionClause, // of the access method. Use parameters String[] selectionArgs, // depending on access type. String sortOrder, // Parameters other than URI can be null. ContentValues values, CancellationSignal cancellationSignal) { // Body of access method (see next graphic) }

parameters

return & access

Use appropriate:

Uri matching

Page 94: 04 App Components and APIs

C o n t e n t P ro v i d e r M e t h o d Te m p l a t e // Body of access method – code executed when the method is invoked. { // Define a variable to hold result depending on the type of access. Use one of: Cursor mReturn; // Define Cursor for a query. Uri mReturn; // Define Uri for an insert. int mReturn; // Define integer for row count for an update or delete. String mReturn; // Define String for MIME type for a getType. // Perform database access operation based on the method parameters // which were given values by the Content Interface. . . . // Prepare for access mReturn = database.access(parameters . . . ) // Access SQLite database & get return // Perform Notification to set callbacks for access type. mReturn.setNotificationUri(getContext().getContentResolver(), uri); // query getContext().getContentResolver().notifyChange(uri, null); // update, delete, insert // Return result return mReturn // Return result for access. }

return

Use appropriate:

notification

access

Page 95: 04 App Components and APIs

A c t i v i t y L i fe c yc l e M e t h o d s a n d Ty p i c a l U s e s

onStart() • Register Broadcast

Receiver

• Reinitialize states

onResume() • Register Broadcast

Receivers

• Restore variables

• Restart animations

• Lightweight code

onCreate() • Must be implemented

• Call setContentView()

• Initialize display layout

• Initialize variables

• Start background thread

onPause() • Commit changes

• Save variables

• Save preferences

• Stop animations

• Unregister Broadcast

Receivers

• Lightweight code

onStop() • Close server

connections

• Free resources

• Unregister

Broadcast

Receiver

onDestroy() • Close databases

• Release remaining

resources

• Stop background thread

onRestart() • Open server

connections

• Allocate

resources

Portions of this page are

reproduced from work created

and shared by the Android Open

Source Project and used

according to terms described in

the Creative Commons 2.5

Attribution License.

http://developer.android.com/guide/components

/activities.html#ImplementingLifecycleCallbacks

Implementing Lifecycle Callbacks

Page 96: 04 App Components and APIs

B ro a d c a st Re c e i ve rs

Activities Content

Providers

Services Broadcast Receivers

Page 98: 04 App Components and APIs

S e n d i n g a B ro a d c a st

Intent intent = new Intent(); // Instantiate Intent object intent.setAction(“com.donkcowan.specialaction”); // Set action using a custom intent sendBroadcast(intent); // Send broadcast with intent

Variations on sendBroadcast()

AsUser: Allows you to specify the user the broadcast will be sent to.

Ordered: Intent is delivered to BroadcastReceivers one at a time.

Sticky: Intent stays around after the broadcast is complete

receiverPermission: Parameter that allows an optional required permission to be enforced.

Simple sendBroadcast() example for a custom intent

Page 99: 04 App Components and APIs

Ke y O b j e c t s U s e d w i t h C o n t e n t P ro v i d e rs

Content Provider

Manages access to Database and responds to Content Interface

ContentProvider ContentResolver query() insert() update() delete() getType()

Content

Manager

Content

User

SQLite Database management and access

SQLiteDatabase SQLiteQueryBuilder SQLiteOpenHelper

Thread

Optional background thread for long running content access operations

Process

Content Interface

Manages access to ContentProvider

ContentResolver query() insert() update() delete() getType()

Remote Content

Thread Process

Intents startActivity()

Values Uri Cursor

Adapters SimpleCursorAdapter

setListAdapter

Views ListView EditText

Listeners onClick()

Activities

Database

Data Provides access to the result set returned by a database query

Cursor ContentValues Uri ContentResolver

User

Interface

Files