SlideShare une entreprise Scribd logo
1  sur  70
Intents
Ilio Catallo, Eleonora Ciceri – Politecnico di Milano
ilio.catallo@polimi.it, eleonora.ciceri@polimi.it
Activities are tasks
¤ Each Activity should be associated with a specific task
2
view
activity
I can take
pictures
from the
camera
Applications are collection of
activities
¤ Applications are made of different activities, each of
which with its own responsibility
3
view
activity
view
activity I can take
pictures
from the
camera
I allow
users to
compose
new notes
Activities should cooperate
¤ From time to time, an activity may be required to perform
a task out of its set of responsibilities
4
view
activity
view
activity
I can’t
take a
picture by
myself
Activities should cooperate
¤ Wouldn’t it be great if Activities could cooperate?
5
view
activity
view
activity
I’ll back
you up
Let me ask
for help
help request
Activities should cooperate
¤ Wouldn’t it be great if Activities could cooperate?
6
view
activity
view
activity
Here’s your
picture
Thank you!
Picture
Intents
7
Intents
¤ Intents are messages that are passed between
components
8
intent
view
activity
activity
view
Intents
¤ A component may ask another component to execute
some action on its behalf
9
intent
view
activity
activity
view
Intents
¤ The message contains a description of the action to be
performed
10
intent
view
activity
activity
view
Intents
¤ As such, an intent always involves two subjects
11
intent
view
activity
activity
view
Intents
¤ The sender, which wants an action to be performed and
thus publishes a message
12
intent
activity
view
view
activity
Intents
¤ The receiver, which is any component capable of
performing the requested action
13
intent
view
activity
view
activity
What Intents are good at
¤ Actions can be of different type:
¤ Taking pictures from the camera
¤ Starting a new web search
¤ Sending e-mails
¤ Sending SMS’s
¤ Each of these actions requires the execution of the
associated Activity
14
ExampleofAction
15
Intent
Action: play video
Browser application YouTube application
Types of Intents
16
Two ways of launching Activities...
¤ The calling Activity has only two ways of launching a
second Activity
17
view
activity 1
view
activity 2
...by name
¤ By name: The calling Activity knows the exact name of
the Activity to launch
18
view
activity 1
view
activity 2
Start
activity 2
...or by action
¤ By action: The calling Activity wants something to be
done (e.g., taking a picture)
19
view
activity 1
view
activity 2
I need to
take a
picture
Implicit and Explicit intents
¤ Consequently, Android provides two kinds of Intents:
¤ Explicit intents, which specify the exact Activity to which the
Intent should be given
¤ Implicit Intents, which do not declare the name of the
Activity to start, but instead declare an action to perform
20
Start
activity 2
Explicit intent
Take a
picture
Implicit intent
Intent resolution mechanism
¤ For implicit intents, the system determines which Activity is
best to run based on the Intent’s fields
¤ If more than one Activity can handle the Intent, a dialog
for the user to select which app to use is displayed
21
Intent resolution mechanism
22
Activity 1
Activity 2
Intent
Resolution
Explicit Intent:
“Execute Activity3”
Implicit Intent:
“Send a new e-mail”
Activity 3
Fancy
e-mail
client
Humble
e-mail
client
User decides which
client to use
Launching new Activities
23
Launching a new Activity
¤ An Activity asks for the intervention of a second Activity
by invoking on itself the startActivity() method
24
view
activity
view
activity
startActivity()
Launching a new Activity
¤ An Activity asks for the intervention of a second Activity
by invoking on itself the startActivity() method
25
view
activity
view
activity
startActivity()
intent
Launching a new Activity
¤ Activity class:
26
public class Activity {
public Activity() {...}
public void startActivity(Intent intent) {...}
...
}
startActivity()
launches a new Activity
based on the provided
Intent object
Launching a new Activity
¤ First, the calling Activity forges an Intent object that
contains the description of the needed action
¤ The Intent could be either implicit or explicit
27
Start
activity 2
Explicit intent
Take a
picture
Implicit intent
Launching a new Activity
¤ Once ready, the Intent object is passed to
startActivity()
28
public void startActivity(Intent intent) {...}
Start
activity 2
Explicit intent
Take a
picture
Implicit intent
Launching a new Activity
¤ Once the startActivity() method is invoked
¤ Implicit intents: the resolution mechanism identifies the
Activity that best matches the intent fields
¤ Explicit intents: the system receives the call and starts an
instance of the Activity specifiedby the Intent
29
30
How to create Intents?
Intent class
¤ Intent class:
31
public class Intent {
public Intent(Context context, Class<?> cls) {...}
public Intent(String action, Uri uri) {...}
...
}
Explicit Intent
constructor
Implicit Intent
constructor
Creating explicit Intents
¤ Explicit Intents are typically used for launching new Activities
within the same application
¤ Nothing in the Intent object other than the name of the
Activity to be launched matters
¤ All other fields (action, data, category) are null
32
Intent intent = new Intent(this, TargetActivity.class);
Context
The calling Activity is used as a Context
object in order to determine the
package where to look for the
NewActivity class
Creating implicit Intents
¤ Each implicit Intent contains information useful to the
receiver for performing the job:
¤ Action: the job that the sender can require to perform
¤ Data: the data on which the job will run
¤ Category: the execution requirements (e.g., of being
executed in a browser)
33
Intent in = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:0223993669"));
Action
Making a phone call
Data
The phone number
Adding extra parameters
¤ It is possible to pass some parameters to the started
Activity by adding them as extra content of the
Intent
34
Intent intent = ...
intent.putExtra(EXTRA_MESSAGE, myMessage);
startActivity(intent);
Receiving an Intent
35
Receiving an Intent
¤ Within the just-started Activity, you can inspect the
received Intent by using the getIntent() method
¤ Useful to retrieve the data contained in the Intent
¤ This is usually done in the onCreate() method of the new
Activity
36
Intent intent = getIntent();
String message = intent.getStringExtra(EXTRA_MESSAGE);
Receiving implicit Intents
¤ How to inform the system that an Activity can handle a
specific type of implict Intent?
¤ This can be done by advertising that a given Activity can
manage a specific implicit Intent, i.e., by associating the
Activity with an Intent filter
37
Intent filter
¤ An Intent filter:
¤ declares the capability of an Activity of receiving implicit
Intents of a specific type
¤ delimits the Intents an Activity can handle
38
view
activity I can take
pictures
from the
camera
Example:
dialing a number
¤ In order to declare an Intent filter, you need to add an
<intent-filter> element in your manifest file for the
corresponding <activity> element
¤ Example: we declare that the Activity can act as a dialer
39
<intent-filter>
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="tel"/>
</intent-filter>
Example:
dialing a number
¤ Everytime an implicit intent of type
android.intent.action.DIAL is casted:
¤ Our Activity is listed as a candidate:
40
Intent in = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:0223993669"));
startActivity(in);
Example: dialing a number (2)
!  Everytime an implicit intent of type
android.intent.action.DIAL is casted:
!  Our Activity is listed as a candidate:
26
Intent in = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:0223993669"));
startActivity(in);
Example:
launching an app
¤ Look in your AndroidManifest.xml file:
¤ You will find an intent filter associated with the main Activity
¤ The intent filters declares that the main activity can receive
an implicit Intent coming from the Launcher
¤ Such a implicit intent corresponds to the user’s action of
launching the application
41
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Returning data from an Activity
42
Requesting a result from an Activity
¤ Starting another Activity does not have to be one-way
¤ You can start a second Activity and receive a result back
¤ Examples
¤ Start the camera and receive the photo as a result
¤ Start the People app and receive a contact details as a
result
43
Requesting a result from an Activity
44
Activity 1
Camera
Activity
Implicit Intent:
“Take a picture”
Calling (first)
Activity
Called (second)
Activity
Activity class
¤ Activity class:
45
public class Activity {
public Activity() {...}
public void startActivity(Intent intent) {...}
public void startActivityForResult(Intent intent,
int requestCode) {...}
...
}
startActivityForResult()
launches a new Activity,
expecting to receive a result
back
Requesting a result from an Activity
¤ The Intent you pass is the same you could use to start
an Activity without requiring a result back
¤ Just call startActivityForResult() instead of
startActivity()
¤ You need to pass an additional integer argument, that
represents a request code that identifies the request
46
Intent intent = ...
startActivityForResult(intent, MY_REQUEST_CODE);
Returned data
¤ Once the user is done with the called Activity, the result
will be sent back to the first Activity
¤ Along with the actual result, additional information is
returned from the called Activity to the calling Activity:
¤ The request code originally sent by the calling Activity
¤ A result code to notify that the operation in the called
Activity has been successful
¤ Insight: Activity result codes have the same role as the
HTTP status codes
47
Returned data
48
Activity 1
Camera
Activity
(android.media.action.IMAGE_CAPTURE,
TAKE_PICTURE*)
Calling (first)
Activity
Called (second)
Activity
< , TAKE_PICTURE, RESULT_OK>
* where TAKE_PICTURE is a int constant
representing the request code
Activity class
¤ Activity class:
49
public class Activity {
public Activity() {...}
public void startActivity(Intent intent) {...}
public void startActivityForResult(Intent intent,
int requestCode) {...}
protected void onActivityResult(int requestCode,
int resultCode,
Intent data) {...}
...
} result is processed in
onActivityResult()
Processing the returned data
¤ When the second Activity returns, the system invokes the
onActivityResult() method on the calling Activity
¤ The data are sent back to the calling Activity as an Intent
50
@Override
protected void onActivityResult(int requestCode,
int resultCode,Intent data) {
if (requestCode == MY_REQUEST_CODE)
if (resultCode == RESULT_OK)
[...]
}
Role of the request code
¤ The calling Activity uses different request codes to
distinguish between different types of requests
¤ When receiving a result, the calling Activity uses the request
code to identify the provenance of the result
¤ The request codes only makes sense for the calling
Activity, while they do not have any particular meaning
for the called Activity
51
Role of the request code
52
Activity 1
Activity 4
Activity 3
Activity 2
Request code: 1
Request code: 2
Request code: 3
Role of the request code
53
Request code: 1
Activity 2
Activity 1
Activity 4
Activity 3
The data come
from Activity 2, as
the request code
bundled with the
result is 1
Returning data from an Activity
¤ In case the called Activity is part of our application, we
have to deal also with the problem of returning data to
the calling Activity
¤ We need to:
¤ Perform the operation for which we launched the second
Activity
¤ Pack the result into an Intent object
¤ Determine the result code
¤ Terminate the called Activity
54
Performing the operation in the
called Activity
¤ An Activity represents a task the user can achieve
¤ To this end, it may be possible for the calling Activity to
provide some parameters to the second Activity
¤ These parameters are sent within the Intent as extra’s
¤ We already know how to inspect the triggering Intent
within the second Activity:
55
Intent intent = getIntent();
String message = intent.getStringExtra(EXTRA_MESSAGE);
Packing the result into an Intent
object
¤ The called Activity produces a result of some kind
¤ These data can be packed into an Intent by using the
Intent’s putExtra() method
56
Intent intent = new Intent();
intent.putExtra("KeyForResult1", result1);
intent.putExtra("KeyForResult2", result2);
We use the default
constructor, since we do
not know anything about
the calling Activity (but the
OS knows for us)
Activity class
¤ Activity class:
57
public class Activity {
public Activity() {...}
public void startActivity(Intent intent) {...}
public void startActivityForResult(Intent intent,
int requestCode) {...}
protected void onActivityResult(int requestCode,
int resultCode,
Intent data) {...}
public final void setResult(int resultCode,
Intent data) {...}
}
set the result
that the
Activity will
return to the
caller
Determining the result code
¤ The operation performed in the called Activity may
succeed or fail, and the resulting data may change
accordingly
¤ You can set the result and the corresponding result code
as follows:
58
Intent data = new Intent();
data.putExtra(...)
....
setResult(RESULT_OK, data);
We use the default
constructor, since we do
not know anything about
the calling Activity (but the
OS knows for us)
Terminating the called Activity
¤ The Intent containing the result will not be fired until the
called Activity is running
¤ It is the Operating System (OS) that passes Intents between
different components
¤ No communication occurs as long as the control does not
return to the OS
¤ Hence, when the user is done with the Activity, it has to
be terminated
59
Terminating the called Activity
¤ Usually, it is up to the Operating System to decide when
to terminate an Activity
¤ However, is some cases the user performs an operation of
the UI that indicates that he is done with the current Activity
¤ To manually terminate an Activity we can use the
finish() method
60
Intent data = new Intent();
data.putExtra(...)
....
setResult(RESULT_OK, data);
finish()
Activity class
¤ Activity class:
61
public class Activity {
public Activity() {...}
public void startActivity(Intent intent) {...}
public void startActivityForResult(Intent intent,
int requestCode) {...}
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {...}
public final void setResult (int resultCode, Intent data) {...}
public void finish () {...}
}
Call this when your
activity is done and
should be closed.
TakeNotes V3
62
TakeNotes v3:
require a new to do
¤ When the + button is clicked, a new to do is required
¤ The input form containing the to do data is launched in a
second Activity (AddToDoActivity)
¤ We require the execution of the second Activity, expecting it
to return a result (i.e., the to do description)
63
Intent intent = new Intent(this, AddToDoActivity.class);
startActivityForResult(intent, REQUIRE_NEW_TODO);
Request code, stored in ToDoListActivity.java:
public static final int REQUIRE_NEW_TODO = 0;
TakeNotes v3:
input the new to do
¤ The interface is built in the layout file (res/layout/)
64
<LinearLayout [...]>
<EditText android:id="@+id/toDoContent"
[...]/>
<Button [...]
android:onClick="addToDoToList"/>
</LinearLayout>
TakeNotes v3:
returning the result
¤ When the user clicks on the button, the to-do item has to
return to the first activity (ToDoListActivity)
¤ To do so, we collect the result from the
AddToDoActivity activity and send it back with an
Intent
¤ The Intent will report the to-do description as extra content
¤ Once the Intent is sent, the AddToDoActivity activity is
closed using the finish() instruction
65
TakeNotes v3:
returning the result
66
public void addToDoToList(View view) {
Intent intent = new Intent(this, ToDoListActivity.class);
EditText editText = (EditText) findViewById(R.id.toDoContent);
String newContent = editText.getText().toString();
intent.putExtra(TODO_CONTENT, newContent);
setResult(RESULT_OK, intent);
finish();
}
Called when the
button is pressed
Terminate the Activity and
release the intent
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUIRE_NEW_TODO &&
resultCode == RESULT_OK)
if (intent != null)
addNewToDoToList(
intent.getStringExtra(AddToDoActivity.TODO_CONTENT));
}
TakeNotes v3:
receiving the result
67
¤ The result is now returned to ToDoListActivity and
needs to be processed
¤ All the results coming from an Intent are collected by the
onActivityResult method
Verify the request
code so as to identify
the correct result
TakeNotes v3
adding to-do’s
¤ We retrieved the item description, not the checkbox
¤ The next steps are:
¤ Build the checkbox
¤ Add the checkbox to the list linear layout
68
CheckBox newToDoCheckBox = new CheckBox(this);
newToDoCheckBox.setText(message);
addOnClickListener(newToDoCheckBox);
LinearLayout linearLayout = (LinearLayout)
findViewById(R.id.checkBoxContainer);
linearLayout.addView(newToDoCheckBox);
See TakeNotes v2
References
69
References
¤ Android Training, Starting an Activity
http://developer.android.com/training/basics/firstapp/starting-
activity.html
¤ Android Training, Getting a Result from an Activity
http://developer.android.com/training/basics/intents/result.html
¤ Android API Guides, Intent and Intent Filters
http://developer.android.com/guide/components/intents-
filters.html
¤ Android Training, Sending the User to Another App
http://developer.android.com/training/basics/intents/sending.html
¤ Android Training, Allowing other Apps to Start Your Activity
http://developer.android.com/training/basics/intents/filters.html
70

Contenu connexe

Tendances

Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Android graphics
Android graphicsAndroid graphics
Android graphicsKrazy Koder
 
Android animation
Android animationAndroid animation
Android animationKrazy Koder
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaAndroid | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaJAX London
 
Shared preferences
Shared preferencesShared preferences
Shared preferencesSourabh Sahu
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycleSokngim Sa
 
Android activity
Android activityAndroid activity
Android activityKrazy Koder
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
android layouts
android layoutsandroid layouts
android layoutsDeepa Rani
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 

Tendances (20)

Fragment
Fragment Fragment
Fragment
 
05 intent
05 intent05 intent
05 intent
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
 
Android intent
Android intentAndroid intent
Android intent
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Android graphics
Android graphicsAndroid graphics
Android graphics
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
 
Android animation
Android animationAndroid animation
Android animation
 
Android Services
Android ServicesAndroid Services
Android Services
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaAndroid | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
 
Shared preferences
Shared preferencesShared preferences
Shared preferences
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
Angular
AngularAngular
Angular
 
Android activity
Android activityAndroid activity
Android activity
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
android layouts
android layoutsandroid layouts
android layouts
 
Notification android
Notification androidNotification android
Notification android
 
Activity lifecycle
Activity lifecycleActivity lifecycle
Activity lifecycle
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 

En vedette

Android Lesson 3 - Intent
Android Lesson 3 - IntentAndroid Lesson 3 - Intent
Android Lesson 3 - IntentDaniela Da Cruz
 
Intent in android
Intent in androidIntent in android
Intent in androidDurai S
 
Android Application Fundamentals
Android Application FundamentalsAndroid Application Fundamentals
Android Application FundamentalsVikalp Jain
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAhsanul Karim
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and ActivityNikmesoft Ltd
 
Android Activity Transition(ShareElement)
Android Activity Transition(ShareElement)Android Activity Transition(ShareElement)
Android Activity Transition(ShareElement)Ted Liang
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recieversUtkarsh Mankad
 
Android User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAndroid User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAhsanul Karim
 
Open Intents - Android Intents Mechanism and Dependency Management
Open Intents - Android Intents Mechanism and Dependency ManagementOpen Intents - Android Intents Mechanism and Dependency Management
Open Intents - Android Intents Mechanism and Dependency ManagementFriedger Müffke
 
Gradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of FriendsGradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of FriendsRomin Irani
 
Android Fundamentals - Day 2
Android Fundamentals - Day 2Android Fundamentals - Day 2
Android Fundamentals - Day 2Mohammad Tarek
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentalsAmr Salman
 
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...Deepu S Nath
 
Gradle for Android Developers
Gradle for Android DevelopersGradle for Android Developers
Gradle for Android DevelopersJosiah Renaudin
 
Introduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryIntroduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryKaushal Dhruw
 
Android gradle-build-system-overview
Android gradle-build-system-overviewAndroid gradle-build-system-overview
Android gradle-build-system-overviewKevin He
 

En vedette (18)

Android Lesson 3 - Intent
Android Lesson 3 - IntentAndroid Lesson 3 - Intent
Android Lesson 3 - Intent
 
Intent in android
Intent in androidIntent in android
Intent in android
 
Android Application Fundamentals
Android Application FundamentalsAndroid Application Fundamentals
Android Application Fundamentals
 
Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and Activity
 
Android Activity Transition(ShareElement)
Android Activity Transition(ShareElement)Android Activity Transition(ShareElement)
Android Activity Transition(ShareElement)
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
Android User Interface: Basic Form Widgets
Android User Interface: Basic Form WidgetsAndroid User Interface: Basic Form Widgets
Android User Interface: Basic Form Widgets
 
Open Intents - Android Intents Mechanism and Dependency Management
Open Intents - Android Intents Mechanism and Dependency ManagementOpen Intents - Android Intents Mechanism and Dependency Management
Open Intents - Android Intents Mechanism and Dependency Management
 
Gradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of FriendsGradle and Android Studio : Best of Friends
Gradle and Android Studio : Best of Friends
 
Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
 
Android Fundamentals - Day 2
Android Fundamentals - Day 2Android Fundamentals - Day 2
Android Fundamentals - Day 2
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentals
 
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
 
Gradle for Android Developers
Gradle for Android DevelopersGradle for Android Developers
Gradle for Android Developers
 
Introduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryIntroduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding library
 
Android gradle-build-system-overview
Android gradle-build-system-overviewAndroid gradle-build-system-overview
Android gradle-build-system-overview
 

Similaire à Intents in Android

Pertemuan 03 - Activities and intents.pptx
Pertemuan 03 - Activities and intents.pptxPertemuan 03 - Activities and intents.pptx
Pertemuan 03 - Activities and intents.pptxMUHAMMADRIFKIPERMANA2
 
Day 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through ActivitiesDay 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through ActivitiesAhsanul Karim
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAnuchit Chalothorn
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intentDiego Grancini
 
android_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semandroid_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semaswinbiju1652
 
Android - Intents - Mazenet Solution
Android - Intents - Mazenet SolutionAndroid - Intents - Mazenet Solution
Android - Intents - Mazenet SolutionMazenetsolution
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Androidma-polimi
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database faiz324545
 
Ch5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetCh5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetShih-Hsiang Lin
 
Intent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).pptIntent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).pptBirukMarkos
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)Oum Saokosal
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & DatabasesMuhammad Sajid
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intentPERKYTORIALS
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intentMengChun Lam
 

Similaire à Intents in Android (20)

Activity & Shared Preference
Activity & Shared PreferenceActivity & Shared Preference
Activity & Shared Preference
 
Pertemuan 03 - Activities and intents.pptx
Pertemuan 03 - Activities and intents.pptxPertemuan 03 - Activities and intents.pptx
Pertemuan 03 - Activities and intents.pptx
 
Day 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through ActivitiesDay 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through Activities
 
ANDROID
ANDROIDANDROID
ANDROID
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; Share
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intent
 
unit3.pptx
unit3.pptxunit3.pptx
unit3.pptx
 
android_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semandroid_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last sem
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Android - Intents - Mazenet Solution
Android - Intents - Mazenet SolutionAndroid - Intents - Mazenet Solution
Android - Intents - Mazenet Solution
 
Events and Listeners in Android
Events and Listeners in AndroidEvents and Listeners in Android
Events and Listeners in Android
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database
 
Ch5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internetCh5 intent broadcast receivers adapters and internet
Ch5 intent broadcast receivers adapters and internet
 
Android intents in android application-chapter7
Android intents in android application-chapter7Android intents in android application-chapter7
Android intents in android application-chapter7
 
Intent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).pptIntent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).ppt
 
Intents are Awesome
Intents are AwesomeIntents are Awesome
Intents are Awesome
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intent
 

Dernier

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Dernier (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Intents in Android

  • 1. Intents Ilio Catallo, Eleonora Ciceri – Politecnico di Milano ilio.catallo@polimi.it, eleonora.ciceri@polimi.it
  • 2. Activities are tasks ¤ Each Activity should be associated with a specific task 2 view activity I can take pictures from the camera
  • 3. Applications are collection of activities ¤ Applications are made of different activities, each of which with its own responsibility 3 view activity view activity I can take pictures from the camera I allow users to compose new notes
  • 4. Activities should cooperate ¤ From time to time, an activity may be required to perform a task out of its set of responsibilities 4 view activity view activity I can’t take a picture by myself
  • 5. Activities should cooperate ¤ Wouldn’t it be great if Activities could cooperate? 5 view activity view activity I’ll back you up Let me ask for help help request
  • 6. Activities should cooperate ¤ Wouldn’t it be great if Activities could cooperate? 6 view activity view activity Here’s your picture Thank you! Picture
  • 8. Intents ¤ Intents are messages that are passed between components 8 intent view activity activity view
  • 9. Intents ¤ A component may ask another component to execute some action on its behalf 9 intent view activity activity view
  • 10. Intents ¤ The message contains a description of the action to be performed 10 intent view activity activity view
  • 11. Intents ¤ As such, an intent always involves two subjects 11 intent view activity activity view
  • 12. Intents ¤ The sender, which wants an action to be performed and thus publishes a message 12 intent activity view view activity
  • 13. Intents ¤ The receiver, which is any component capable of performing the requested action 13 intent view activity view activity
  • 14. What Intents are good at ¤ Actions can be of different type: ¤ Taking pictures from the camera ¤ Starting a new web search ¤ Sending e-mails ¤ Sending SMS’s ¤ Each of these actions requires the execution of the associated Activity 14
  • 15. ExampleofAction 15 Intent Action: play video Browser application YouTube application
  • 17. Two ways of launching Activities... ¤ The calling Activity has only two ways of launching a second Activity 17 view activity 1 view activity 2
  • 18. ...by name ¤ By name: The calling Activity knows the exact name of the Activity to launch 18 view activity 1 view activity 2 Start activity 2
  • 19. ...or by action ¤ By action: The calling Activity wants something to be done (e.g., taking a picture) 19 view activity 1 view activity 2 I need to take a picture
  • 20. Implicit and Explicit intents ¤ Consequently, Android provides two kinds of Intents: ¤ Explicit intents, which specify the exact Activity to which the Intent should be given ¤ Implicit Intents, which do not declare the name of the Activity to start, but instead declare an action to perform 20 Start activity 2 Explicit intent Take a picture Implicit intent
  • 21. Intent resolution mechanism ¤ For implicit intents, the system determines which Activity is best to run based on the Intent’s fields ¤ If more than one Activity can handle the Intent, a dialog for the user to select which app to use is displayed 21
  • 22. Intent resolution mechanism 22 Activity 1 Activity 2 Intent Resolution Explicit Intent: “Execute Activity3” Implicit Intent: “Send a new e-mail” Activity 3 Fancy e-mail client Humble e-mail client User decides which client to use
  • 24. Launching a new Activity ¤ An Activity asks for the intervention of a second Activity by invoking on itself the startActivity() method 24 view activity view activity startActivity()
  • 25. Launching a new Activity ¤ An Activity asks for the intervention of a second Activity by invoking on itself the startActivity() method 25 view activity view activity startActivity() intent
  • 26. Launching a new Activity ¤ Activity class: 26 public class Activity { public Activity() {...} public void startActivity(Intent intent) {...} ... } startActivity() launches a new Activity based on the provided Intent object
  • 27. Launching a new Activity ¤ First, the calling Activity forges an Intent object that contains the description of the needed action ¤ The Intent could be either implicit or explicit 27 Start activity 2 Explicit intent Take a picture Implicit intent
  • 28. Launching a new Activity ¤ Once ready, the Intent object is passed to startActivity() 28 public void startActivity(Intent intent) {...} Start activity 2 Explicit intent Take a picture Implicit intent
  • 29. Launching a new Activity ¤ Once the startActivity() method is invoked ¤ Implicit intents: the resolution mechanism identifies the Activity that best matches the intent fields ¤ Explicit intents: the system receives the call and starts an instance of the Activity specifiedby the Intent 29
  • 30. 30 How to create Intents?
  • 31. Intent class ¤ Intent class: 31 public class Intent { public Intent(Context context, Class<?> cls) {...} public Intent(String action, Uri uri) {...} ... } Explicit Intent constructor Implicit Intent constructor
  • 32. Creating explicit Intents ¤ Explicit Intents are typically used for launching new Activities within the same application ¤ Nothing in the Intent object other than the name of the Activity to be launched matters ¤ All other fields (action, data, category) are null 32 Intent intent = new Intent(this, TargetActivity.class); Context The calling Activity is used as a Context object in order to determine the package where to look for the NewActivity class
  • 33. Creating implicit Intents ¤ Each implicit Intent contains information useful to the receiver for performing the job: ¤ Action: the job that the sender can require to perform ¤ Data: the data on which the job will run ¤ Category: the execution requirements (e.g., of being executed in a browser) 33 Intent in = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0223993669")); Action Making a phone call Data The phone number
  • 34. Adding extra parameters ¤ It is possible to pass some parameters to the started Activity by adding them as extra content of the Intent 34 Intent intent = ... intent.putExtra(EXTRA_MESSAGE, myMessage); startActivity(intent);
  • 36. Receiving an Intent ¤ Within the just-started Activity, you can inspect the received Intent by using the getIntent() method ¤ Useful to retrieve the data contained in the Intent ¤ This is usually done in the onCreate() method of the new Activity 36 Intent intent = getIntent(); String message = intent.getStringExtra(EXTRA_MESSAGE);
  • 37. Receiving implicit Intents ¤ How to inform the system that an Activity can handle a specific type of implict Intent? ¤ This can be done by advertising that a given Activity can manage a specific implicit Intent, i.e., by associating the Activity with an Intent filter 37
  • 38. Intent filter ¤ An Intent filter: ¤ declares the capability of an Activity of receiving implicit Intents of a specific type ¤ delimits the Intents an Activity can handle 38 view activity I can take pictures from the camera
  • 39. Example: dialing a number ¤ In order to declare an Intent filter, you need to add an <intent-filter> element in your manifest file for the corresponding <activity> element ¤ Example: we declare that the Activity can act as a dialer 39 <intent-filter> <action android:name="android.intent.action.DIAL" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="tel"/> </intent-filter>
  • 40. Example: dialing a number ¤ Everytime an implicit intent of type android.intent.action.DIAL is casted: ¤ Our Activity is listed as a candidate: 40 Intent in = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0223993669")); startActivity(in); Example: dialing a number (2) !  Everytime an implicit intent of type android.intent.action.DIAL is casted: !  Our Activity is listed as a candidate: 26 Intent in = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0223993669")); startActivity(in);
  • 41. Example: launching an app ¤ Look in your AndroidManifest.xml file: ¤ You will find an intent filter associated with the main Activity ¤ The intent filters declares that the main activity can receive an implicit Intent coming from the Launcher ¤ Such a implicit intent corresponds to the user’s action of launching the application 41 <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
  • 42. Returning data from an Activity 42
  • 43. Requesting a result from an Activity ¤ Starting another Activity does not have to be one-way ¤ You can start a second Activity and receive a result back ¤ Examples ¤ Start the camera and receive the photo as a result ¤ Start the People app and receive a contact details as a result 43
  • 44. Requesting a result from an Activity 44 Activity 1 Camera Activity Implicit Intent: “Take a picture” Calling (first) Activity Called (second) Activity
  • 45. Activity class ¤ Activity class: 45 public class Activity { public Activity() {...} public void startActivity(Intent intent) {...} public void startActivityForResult(Intent intent, int requestCode) {...} ... } startActivityForResult() launches a new Activity, expecting to receive a result back
  • 46. Requesting a result from an Activity ¤ The Intent you pass is the same you could use to start an Activity without requiring a result back ¤ Just call startActivityForResult() instead of startActivity() ¤ You need to pass an additional integer argument, that represents a request code that identifies the request 46 Intent intent = ... startActivityForResult(intent, MY_REQUEST_CODE);
  • 47. Returned data ¤ Once the user is done with the called Activity, the result will be sent back to the first Activity ¤ Along with the actual result, additional information is returned from the called Activity to the calling Activity: ¤ The request code originally sent by the calling Activity ¤ A result code to notify that the operation in the called Activity has been successful ¤ Insight: Activity result codes have the same role as the HTTP status codes 47
  • 48. Returned data 48 Activity 1 Camera Activity (android.media.action.IMAGE_CAPTURE, TAKE_PICTURE*) Calling (first) Activity Called (second) Activity < , TAKE_PICTURE, RESULT_OK> * where TAKE_PICTURE is a int constant representing the request code
  • 49. Activity class ¤ Activity class: 49 public class Activity { public Activity() {...} public void startActivity(Intent intent) {...} public void startActivityForResult(Intent intent, int requestCode) {...} protected void onActivityResult(int requestCode, int resultCode, Intent data) {...} ... } result is processed in onActivityResult()
  • 50. Processing the returned data ¤ When the second Activity returns, the system invokes the onActivityResult() method on the calling Activity ¤ The data are sent back to the calling Activity as an Intent 50 @Override protected void onActivityResult(int requestCode, int resultCode,Intent data) { if (requestCode == MY_REQUEST_CODE) if (resultCode == RESULT_OK) [...] }
  • 51. Role of the request code ¤ The calling Activity uses different request codes to distinguish between different types of requests ¤ When receiving a result, the calling Activity uses the request code to identify the provenance of the result ¤ The request codes only makes sense for the calling Activity, while they do not have any particular meaning for the called Activity 51
  • 52. Role of the request code 52 Activity 1 Activity 4 Activity 3 Activity 2 Request code: 1 Request code: 2 Request code: 3
  • 53. Role of the request code 53 Request code: 1 Activity 2 Activity 1 Activity 4 Activity 3 The data come from Activity 2, as the request code bundled with the result is 1
  • 54. Returning data from an Activity ¤ In case the called Activity is part of our application, we have to deal also with the problem of returning data to the calling Activity ¤ We need to: ¤ Perform the operation for which we launched the second Activity ¤ Pack the result into an Intent object ¤ Determine the result code ¤ Terminate the called Activity 54
  • 55. Performing the operation in the called Activity ¤ An Activity represents a task the user can achieve ¤ To this end, it may be possible for the calling Activity to provide some parameters to the second Activity ¤ These parameters are sent within the Intent as extra’s ¤ We already know how to inspect the triggering Intent within the second Activity: 55 Intent intent = getIntent(); String message = intent.getStringExtra(EXTRA_MESSAGE);
  • 56. Packing the result into an Intent object ¤ The called Activity produces a result of some kind ¤ These data can be packed into an Intent by using the Intent’s putExtra() method 56 Intent intent = new Intent(); intent.putExtra("KeyForResult1", result1); intent.putExtra("KeyForResult2", result2); We use the default constructor, since we do not know anything about the calling Activity (but the OS knows for us)
  • 57. Activity class ¤ Activity class: 57 public class Activity { public Activity() {...} public void startActivity(Intent intent) {...} public void startActivityForResult(Intent intent, int requestCode) {...} protected void onActivityResult(int requestCode, int resultCode, Intent data) {...} public final void setResult(int resultCode, Intent data) {...} } set the result that the Activity will return to the caller
  • 58. Determining the result code ¤ The operation performed in the called Activity may succeed or fail, and the resulting data may change accordingly ¤ You can set the result and the corresponding result code as follows: 58 Intent data = new Intent(); data.putExtra(...) .... setResult(RESULT_OK, data); We use the default constructor, since we do not know anything about the calling Activity (but the OS knows for us)
  • 59. Terminating the called Activity ¤ The Intent containing the result will not be fired until the called Activity is running ¤ It is the Operating System (OS) that passes Intents between different components ¤ No communication occurs as long as the control does not return to the OS ¤ Hence, when the user is done with the Activity, it has to be terminated 59
  • 60. Terminating the called Activity ¤ Usually, it is up to the Operating System to decide when to terminate an Activity ¤ However, is some cases the user performs an operation of the UI that indicates that he is done with the current Activity ¤ To manually terminate an Activity we can use the finish() method 60 Intent data = new Intent(); data.putExtra(...) .... setResult(RESULT_OK, data); finish()
  • 61. Activity class ¤ Activity class: 61 public class Activity { public Activity() {...} public void startActivity(Intent intent) {...} public void startActivityForResult(Intent intent, int requestCode) {...} protected void onActivityResult(int requestCode, int resultCode, Intent data) {...} public final void setResult (int resultCode, Intent data) {...} public void finish () {...} } Call this when your activity is done and should be closed.
  • 63. TakeNotes v3: require a new to do ¤ When the + button is clicked, a new to do is required ¤ The input form containing the to do data is launched in a second Activity (AddToDoActivity) ¤ We require the execution of the second Activity, expecting it to return a result (i.e., the to do description) 63 Intent intent = new Intent(this, AddToDoActivity.class); startActivityForResult(intent, REQUIRE_NEW_TODO); Request code, stored in ToDoListActivity.java: public static final int REQUIRE_NEW_TODO = 0;
  • 64. TakeNotes v3: input the new to do ¤ The interface is built in the layout file (res/layout/) 64 <LinearLayout [...]> <EditText android:id="@+id/toDoContent" [...]/> <Button [...] android:onClick="addToDoToList"/> </LinearLayout>
  • 65. TakeNotes v3: returning the result ¤ When the user clicks on the button, the to-do item has to return to the first activity (ToDoListActivity) ¤ To do so, we collect the result from the AddToDoActivity activity and send it back with an Intent ¤ The Intent will report the to-do description as extra content ¤ Once the Intent is sent, the AddToDoActivity activity is closed using the finish() instruction 65
  • 66. TakeNotes v3: returning the result 66 public void addToDoToList(View view) { Intent intent = new Intent(this, ToDoListActivity.class); EditText editText = (EditText) findViewById(R.id.toDoContent); String newContent = editText.getText().toString(); intent.putExtra(TODO_CONTENT, newContent); setResult(RESULT_OK, intent); finish(); } Called when the button is pressed Terminate the Activity and release the intent
  • 67. @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == REQUIRE_NEW_TODO && resultCode == RESULT_OK) if (intent != null) addNewToDoToList( intent.getStringExtra(AddToDoActivity.TODO_CONTENT)); } TakeNotes v3: receiving the result 67 ¤ The result is now returned to ToDoListActivity and needs to be processed ¤ All the results coming from an Intent are collected by the onActivityResult method Verify the request code so as to identify the correct result
  • 68. TakeNotes v3 adding to-do’s ¤ We retrieved the item description, not the checkbox ¤ The next steps are: ¤ Build the checkbox ¤ Add the checkbox to the list linear layout 68 CheckBox newToDoCheckBox = new CheckBox(this); newToDoCheckBox.setText(message); addOnClickListener(newToDoCheckBox); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.checkBoxContainer); linearLayout.addView(newToDoCheckBox); See TakeNotes v2
  • 70. References ¤ Android Training, Starting an Activity http://developer.android.com/training/basics/firstapp/starting- activity.html ¤ Android Training, Getting a Result from an Activity http://developer.android.com/training/basics/intents/result.html ¤ Android API Guides, Intent and Intent Filters http://developer.android.com/guide/components/intents- filters.html ¤ Android Training, Sending the User to Another App http://developer.android.com/training/basics/intents/sending.html ¤ Android Training, Allowing other Apps to Start Your Activity http://developer.android.com/training/basics/intents/filters.html 70