Activities & Intents - Villanova University

tibburfrogtownΚινητά – Ασύρματες Τεχνολογίες

14 Δεκ 2013 (πριν από 3 χρόνια και 10 μήνες)

90 εμφανίσεις

Activities & Intents
Villanova University / Universidad Nacional de Ingenieria
Android Mobile Device Programming
Summer
2013
Prof EJ Dougherty
Villanova University
College of Engineering
2
Android Applications

Run in its own process & Dalvik runtime

Are kept around for as long as possible

Have limited control over their own lifecycles

Android will kill background/empty processes to free resources for
active foreground processes

Need to listen for changes in state and react accordingly...
event-
driven model

Is a collection of
Activities, Services, ContentProviders or
BroadcastReceivers

By default, all components of the same application run on the
same thread called the
main thread
or
UI thread
3
Application Components
Component
Function
Example
Activity
User focused task
Browse a list of songs to
select a song to play
Service
Background process
Play a song
BroadcastReceiver
Receive messages
Pause song when headset
is unplugged
ContentProvider
Store and retrieve data
Retrieve a list of songs
4

Activity
android.app.Activity
http://developer.android.com/guide/components/activities.html

A single
user focused task
within an application

T
ypically implemented to handle the creation and control of
a specific screen

Consists of a hierarchical collection UI Components called
Views
or
Widgets

Has well defined lifecycle which determines the
application's overall priority

One Activity is active at a time on a device

The
main
activity is presented to the user when launching
the application for the first time
http://developer.android.com/reference/android/app/Activity.html
5
Activity Manager

Creates, destroys, and manages Activities

Keeps track of Activity objects using a LIFO stack, called
Activity
or
Back

Stack

A newly created Activity is placed at the top of stack and is considered
Active
6
7
Activity States

Activities transition through various states while in the
Activity Stack

Active
: visible, has focused and receives user input events

Paused
: visible but does not have focus or receive user input
events, at this point it may be destroyed by Android if running
low on memory

Stopped
: not visible, remains in memory and retains state
information

Android will trigger event callback methods for Activity
state changes
8
Activity Lifecycle
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Running
Visible:
onStart()
to
onStop()
Active:
onResume()
to
onPause()
`
9
public class

MainActivity

extends

Activity
{
// Called when the activity is first created
@Override
protected void

onCreate
(
Bundle

savedInstanceState
) {}
// Called prior to be started again
@Override
protected void
onRestart
() {}
// Called when becoming visible to user
@Override
protected void

onStart
() {}
// Called when active in foreground
@Override
protected void

onResume
() {}
// Called when about to start another activity
@Override
protected void

onPause
() {}
// Called when no longer visible to user
@Override
protected void

onStop
() {}
// Final lifecycle call
@Override
protected void

onDestroy
() {}
 
}
onCreate()
Create UI
onPause()
Commit data
onResume()
Update UI state
onDestroy()
Clean up
10
Implementation of an event callback method
should always call the superclass method first
// Called when about to start another activity
@Override
protected void

onPause
() {
super
.
onPause
();
...
}
11
Saving Activity Data

Use the
onPause()
method to save any uncommitted data that needs
to be persisted to a database or file

The Activity's default implementation will save and restore transient
state data for each View or Widget that has a unique ID (android:id)
defined

Use the
onSaveInstanceState()
method to store any additional
transient state data to memory using a
Bundle
object

This
Bundle
object is available to the
onCreate()
and
onRestoreInstanceState()
methods

Unlike
onPause()
, there is no guarantee that
onSaveInstanceState()
will be
called before the Activity is destroyed
12
Bundle

android.os.Bundle

Is a collection of key-value pairs

Is a type-safe object that is used to store data
in-memory
void

putBoolean
(
String

key
,
boolean

value
)
void

putChar
(
String

key
,
char

value
)
void

putDouble
(
String

key
,
double

value
)
void

putInt
(
String

key
,
int

value
)
void

putString
(
String

key
,
String

value
)
boolean

getBoolean
(
String

key
)
char

getChar
(
String

key
)
double

getDouble
(
String

key
)
int

getInt
(
String

key
)
String

getString
(
String

key
)
http://developer.android.com/reference/android/os/Bundle.html
13
Basic Activity Checklist

Create a new c
lass
that
extends

Activity

Override
the
onCreate()
method

Create a
layout

resource
for the A
ctivity

Add appropriate resources (strings, colors, etc)

Define IDs to automatically save state for any
Views or Widgets

Register the
Activity
in
AndroidManifest.xml
14
Activity Lifecycle Exercise

Create an app that logs a message for each Activity
lifecyle callback method along with the
onSaveInstanceState() method

What does Logcat show when...

The app launches

The orientation of the device changes (
CTL+F12
)

The Back button is pressed

The app is launched again

The Home button is pressed

The app is launched again
15
Application Context
android.content.Context
http://developer.android.com/reference/android/content/Context.html

Provides access to application-wide resources
and system-wide services


Hook” back to the global application
environment

Abstract class whose implementation is
provided by the Android OS

Activities and Services are extended from
Context

16
Intents
17
Intent

android.content.Intent

A powerful asynchronous messaging mechanism
used within or between applications (IPC)

Represents an "intent to do something"

Can request an action to be performed and
optionally, data to be acted upon

Used to broadcast system-wide messages/events
eg battery low, WiFi state change

Explicitly or implicitly activate Activities, Services &
BroadcastReceivers
http://developer.android.com/reference/android/content/Intent.html
18
Starting Another Activity

Create an Intent to explicitly start a specific
Activity using its application component class
name

Followed by a call to the
startActivity()
method
Intent

intent
=
new

Intent
(
this
,
AnotherActivity
.
class
);
startActivity
(
intent
);
19
startActivity() Lifecycle
Transition
onCreate()
onStart()
onResume()
onCreate()
onStart()
OnResume()
onCreate()
onStart()
OnResume()
AnotherActivity callback events
MainActivity callbacks events
MainActivity
AnotherActivity
Activity Stack
onPause()
onStop()
20
Passing Data to an Activity
...
Intent

intent
=
new

Intent
(
this
,
AnotherActivity
.
class
);
intent
.
putExtra
(
“message”
,
“some message”
)
startActivity
(
intent
);
...
@Override
protected

void

onCreate
(
Bundle

saveInstanceState
) {
super
.
onCreate
(
saveInstanceState
);
// Get the message from the intent
Intent

intent
=
getIntent
();
String

msg
=
intent
.
getStringExtra
(
“message”
);
...
}
@Override
protected

void

onCreate
(
Bundle

saveInstanceState
) {
super
.
onCreate
(
saveInstanceState
);
// Get the message from the intent
Intent

intent
=
getIntent
();
String

msg
=
intent
.
getStringExtra
(
“message”
);
...
}
AnotherActivity

An Intent can store additional data as key-
value pairs called
extras

Intent extras are implemented as a
Bundle
MainActivity
21
Start New Activity &
Expecting Results
...
Intent

intent
=
new

Intent
(
this
,
AnotherActivity
.
class
);
startActivityForResult
(
intent
,
MY_REQUEST_CODE
);
...
...
@Override
protected

void

onActivityResult
(
int

requestCode
,
int

resultCode
,
Intent

data
) {
if
(
resultCode
==
Activity
.
RESULT_OK
) {
String

result
=
data
.
getStringExtra
(
"result"
);
// do something interesting with “some data”

}
super
.
onActivityResult
(
requestCode
,
resultCode
,
data
);
}
...
Intent

intent
=
new

Intent
();
intent
.
putExtra
(
“result”
,
“some data”
);
setResult
(
Activity
.
RESULT_OK
,
intent
);
finish
();
...
...
Intent

intent
=
new

Intent
();
intent
.
putExtra
(
“result”
,
“some data”
);
setResult
(
Activity
.
RESULT_OK
,
intent
);
finish
();
...
AnotherActivity
MainActivity
22
Intent Extra Exercise

Create an app with 2 Activities

Each Activity will have an
EditText
widget

The user input collected by the EditText widget
in the 1st Activity will be passed to the 2nd
Activity's EditText widget for update

Any updates will be passed back the 1st
Activity's EditText widget
23
Implicit Intents

Allows anonymous application components to service intent requests
at run time

Action to be performed

Data to be acted on, expressed as a URI reference

Android will attempt to match an implicit Intent with the appropriate
application component

Intent resolution is performed using filters defined for each
application component

What action can be serviced?

Under what circumstance can the action be performed?

What data types can be acted upon?
http://developer.android.com/reference/android/net/Uri.html
URI: Uniform Resource Identifier
24
Common Activity Actions

ACTION_VIEW
launch an app to display the provided data to the user

ACTION_EDIT
launch an app which allows the user to edit the provided data

ACTION_PICK
allow user to pick an item from the provided data

ACTION_WEB_SEARCH
open a browser to perform a search

ACTION_SENDTO
send data to someone

ACTION_DIAL
dial a phone number
sidebar
: Check out [Android SDK]/platforms/android-nn/data/activity_actions.txt
25
ACTION_VIEW Examples
Intent

intent
=
new

Intent
(
Intent
.
ACTION_VIEW
,
Uri
.
parse
(
“http://www.android.com/”
);
Open a web browser and navigates to a given URL
Intent

intent
=
new

Intent
(
Intent
.
ACTION_VIEW
,
Uri
.
parse
(
“content://contacts/people/”
);
Open a contact application to browse contacts
Intent

intent
=
new

Intent
(
Intent
.
ACTION_VIEW
,
Uri
.
parse
(
“tel:18005551212”
);
Open a phone dialer and fills in the given number
Intent

intent
=
new

Intent
(
Intent
.
ACTION_VIEW
,
Uri
.
parse
(
“geo:40.034269,-75.336481”
);
Open a map application to the given coordinates

startActivity
(
intent
);
26
Intent Filters

Informs Android what kind of intents the
application can handle

Each application component can have
separate filters for each task it can perform

Intent filters for Activities and Services are
defined in the
Android Manifest file
using the
<intent-filter>
element
http://developer.android.com/guide/components/intents-filters.html
http://developer.android.com/reference/android/content/IntentFilter.html
27
MAIN & LAUNCHER
Intent Filters

The Activity that can initiate the application has the
android.intent.action.MAIN
intent filter

Application gets started fresh, without a reference to any
particular data

If the Activity also should be represented in the
application launcher, the
android.intent.category.LAUNCHER
intent filter is
specified

Android populates the application launcher by finding all the
activities with intent filters that specify
android.intent.action.MAIN and
android.intent.category.LAUNCHER filters
28
<intent-filter> Example
...
<intent-filter>

<action

android:name=
"android.intent.action.MAIN"

/>

<category

android:name=
"android.intent.category.LAUNCHER"

/>
</intent-filter>
...
This component (ie Activity) is the main point of entry for the application when
launched with no data and should be listed within the application launcher
screen of the device
By default, the Eclipse ADT plug-in will
generate standard intent filters for the
main

Activity
29
...
<intent-filter>

<action

android:name=
"android.intent.action.VIEW"

/>

<category

android:name=
"android.intent.category.DEFAULT"

/>

<category

android:name=
"android.intent.category.BROSWABLE"

/>

<data

android:scheme=
"http"

android:host=
"www.villanova.edu"

/>
</intent-filter>
...
This component will provide a view for any implicit intent containing a URL that
begins with http://www.villanova.edu
http://developer.android.com/guide/topics/manifest/intent-filter-element.html
30
Accessing Intents Received
To retrieve the details of the Intent used to
start the Activity call the
getInent()
method
@Override
protected void
onCreate
(
Bundle
saveInstanceState
) {
super
.onCreate
(
saveInstanceState
);
setConentView
(
R.layout.main
);
// Get the details of the intent
Intent
intent
=
getIntent
();
String
action
=
intent.getAction
();
Uri
data
=
intent.getData
();
...
}
31
To retrieve Intents after the Activity has
started, simply override the
onNewIntent()

callback method
@Override
protected void
onNewIntent
(
Intent
newIntent
) {
super
.
onNewIntent
(
newIntent
);
// Handle intent
...
}
32
Implicit Intent Exercise

Create an app that will use an implicit intent to launch a built-in SMS
activity to send a text

Your main Activity will consist of
2
EditText
views to capture the SMS
number and text and will include a
Button
to invoke the intent

SMS implicit Intent

action:
Intent.ACTION_SENDTO

data: “
smsto:
<number>”

extra:
“sms_body
” key for the text value

Start
2 emulator instances
and note the port numbers

Run your app on one emulator and send an SMS to the other running
instance
sidebar
: Can use
android.telephony.SmsManager
to send text directly from your app