Activities - VNPT eLearning > Home
Download
Report
Transcript Activities - VNPT eLearning > Home
AND101
Introduction to
Xamarin.Android
▸ Nguyen Nhu Hieu
▸ Xamarin Vietnam UserGroup
Objectives
1.
2.
3.
4.
5.
Create a Xamarin.Android project
Decompose an app into Activities
Build an Activity's UI
Write an Activity's behavior
Update your Android SDK
Demonstration
Preview the finished lab exercise
Create a Xamarin.Android project
Tasks
1.
2.
Survey Xamarin.Android features
Create a new project in your IDE
What is a Xamarin.Android app?
v
Xamarin.Android apps are apps built with Xamarin's tools and libraries
UI is made from
Xamarin's wrappers
around the native
Android views
Code is written in C#
Development environment
v
Xamarin.Android apps are coded in C# and built with either
Xamarin Studio or Visual Studio
var employees = new List<Employee>();
var seniors = from e in employees where e.Salary > 50000 select e;
var client = new HttpClient();
var result = await client.GetStringAsync("");
Supports latest C# features like generics, async/await, LINQ, lambda expressions, etc.
F# is also supported; however, this course will use C#.
C# idioms
v
The Xamarin.Android bindings to Android libraries provide a familiar
programming experience for C# developers
EditText input = new EditText(this);
var input = new EditText(this);
String text = input.getText().toString();
string text = input.Text;
input.addTextChangedListener(new TextWatcher() { ... });
input.TextChanged += (sender, e) => { ... };
Java uses get/set methods, listeners, etc.
Xamarin.Android uses properties and
events
Libraries
v
Xamarin.Android apps can use utility classes from three libraries
java.*
android.*
Mono.NET
Xamarin provides
C# wrappers for all
Android Java libraries
Xamarin provides
C# wrappers for
all Android APIs
Includes most .NET
types but not the
entire Mono library
When a new version of Android is released, the Xamarin wrappers are ready within days.
Third-party Java
v
You can use JNI or a Bindings Library to incorporate third-party Java libraries
into your Xamarin.Android app
ArcGIS
PayPal
TritonPlayer
Mapping
Finance
Music
...
A Bindings Library is built on JNI and take some work to set up but is easier to use.
Xamarin.Android project templates
v
Xamarin.Android includes several Android project templates
Xamarin Studio shown,
Visual Studio has
analogous templates
Decompose an app into Activities
Tasks
1.
2.
Define the concept of an Activity
Decompose an app into Activities
App structure
v
An Android app is a collection of collaborating parts called Activities
MyApp
Activity 1
Activity 2
Activity 3
UI
UI
UI
Code
Code
Code
Data files,
images, etc.
What is an Activity?
v
An Activity defines the UI and behavior for a single task
The "Pi" Activity has UI and coded behavior
void OnClick(object sender, EventArgs e)
{
int digits = int.Parse(input.Text);
string result = CalculatePi(digits);
output.Text = result;
}
Activity example: Email
v
The Email app has severalactivities
Messages Activity
Compose Activity
Settings Activity
Flash Quiz
② Name some possible Activities from a contacts app
a)
b)
c)
d)
All contacts
Add new
Details
Edit
Build an Activity's UI
Tasks
1.
2.
Add Views to a Layout in XML
Use the Designer tool
UI elements
v
An Android UI is composed of Views and ViewGroups
Object
View
Controls likebutton,
text box, etc.
Collection views
like lists and grids
ViewGroup
Layout panels that size
and position their children
What is a View?
v
A View is a user-interface component with on-screen visuals and (typically)
behavior such as events
TextView for text display
EditText for text entry
Button
Views are also called widgets. Many are defined in the Android.Widget namespace.
What is a layout?
v
A layout is a container that manages a collection of child views and
calculates their size/position on screen
LinearLayout
Single row or
column
GridLayout
Rows and
columns
We will use only LinearLayout in this course.
RelativeLayout
You specify how
each is positioned
relative toneighbors
What is a layout file
v
UI Views are typically created in an XML layoutfile (.axml)
Pi.axml
Child views are
nested inside a
layout panel
<LinearLayout ... >
<TextView ... />
<EditText ... />
<Button
... />
<TextView ... />
</LinearLayout ... >
What are Resources?
v
Resources are non-code files packaged with your app
Placed in the app's
Resources folder
Note: Xamarin Studio shown, Visual Studio is similar
Where to define your layout files
v
Layout files are a Resource and must be placed in the layout folder
Images in many sizes
for screens of different
pixel densities
Layout files
Strings, colors, etc.
Note: Xamarin Studio shown, Visual Studio is similar
UI Designer
v
Xamarin provides a UI design tool for creating and editing layout XML
Available for
Xamarin Studio
and Visual Studio
Toolbox to add
new Views
with drag-drop
Property editor
View attributes
v
XML attributes are used to set properties on theunderlying objects
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" andro id:orientation="vertical">
<TextView android :text="Enter number of digits:" ... />
...
</LinearLayout>
TextView, EditText, and Button have
a text attribute that sets their Text property
LinearLayout has an orientation
that sets its Orientation property
Attributes names do not always match the underlying property names. See the Android
documentation on each class (e.g. TextView) for a table of the XML attribute names.
Android namespace
v
View attributes must be prefixed with the Android namespace when
defined in XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
<TextView android:text="Enter number of digits:" ... />
...
</LinearLayout>
Prefix with namespace
Prefix with namespace
Android does not require the prefix on Elements so it is common practice to omit it.
View sizing [required]
v LinearLayout requires layout_width and layout_height on every
view
Failure to set width and height yields a runtime exception
View sizing [automatic]
v There are two special values you can use to specify width and height
<LinearLayout ... >
...
<TextView android:layout_width=" match_parent " android:layout_height=" wrap_content " ... />
...
</LinearLayout>
same size as
the parent view
just large enough to
fit around its content
match_parent is the replacement for the equivalent-but-deprecated fill_parent
Group Exercise
Add views to a layout file manually and with the Designer tool
Fixed units-of-measure
v You can use px (screen pixel), pt (1/72"), in (inch), and mm for sizing but
they are not recommended since they do not adapt to different displays
<Button android:layout_width="100px" ... />
Always occupies 100 physical pixels, so it
will be different size on different screens
What is a density-independent pixel?
v
A density-independent pixel (dp) is an abstract unit of measure that maps to
physical pixels at runtime based on screen density
<Button android:layout_width="100dp" ... />
The goal is for this to occupy about the same area on-screen
regardless of the device's screen density. On a high-resolution
screen, this would occupy more than 100 physical pixels.
Baseline density
v
Android chose a baseline density of 160dpi, so 1dp=1px on a 160dpi
screen
<Button android:layout_width="100dp" ... />
On a 160dpi screen, this would occupy 100 physical pixels
The baseline density is derived from the screen of the G1, the first Android device.
Flash Quiz
Flash Quiz
① How many physical pixels (px) would the Button shown below occupy on
a 480dpi screen?
Flash Quiz
① How many physical pixels (px) would the Button shown below occupy on
a 480dpi screen?
a) 300
Summary
1.
2.
Add Views to a Layout in XML
Use the Designer tool
Write an Activity's behavior
Tasks
1.
2.
3.
4.
Designate a Main Activity
See how the Main Activity is listed in
the app Manifest
Load an Activity's UI
Access Views from code
How to define an Activity
v
An Activity has an XML layout file and a C# source file to drive the logic
Pi.axml
<LinearLayout ... >
<TextView
... >
<EditText
... >
<Button
... >
<TextView
... >
</LinearLayout>
UI layout file
PiActivity.cs
[Activity]
public class PiActivity : Activity
{
...
...
}
C# class must inherit from Activity and be
decorated with the ActivityAttribute
Main Activity
v
An app uses the ActivityAttributeto designate an Activity as an entry
point
Only one
activity can
be marked
as the main
entry point
[Activity( MainLauncher = true )]
public class PiActivity : Activity
{
...
}
What is the App Manifest?
v
An app's manifest describes the app to the Android OS
Identity info
Every app must have
a manifest and it
must be named
AndroidManifest.xml
Needed services
Main Activity and the Manifest
v
The Manifest tells Android which is your app's main Activity
<manifest...>
<application...>
<activity ...>
<intent-filter>
<action android:name="android.intent.action .MAIN" />
<category android:name="android.intent.category. LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The MainLauncher property in the ActivityAttribute creates these values in the Manifest.
Android uses these to determine the app entry point and to list this activity on the launcher screen.
Activity initialization
v Override Activity.OnCreate to do your initialization
Must call base or
get an exception
[Activity(MainLauncher = true)]
public class PiActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
...
}
...
}
How to identify a layout file
v
The build process auto-generates a Resource.Layout class that contains
an identifier for each of your layout files
Resource.designer.cs
Use Resource.Layout.Pi
to refer to this layout in code
public partial class Resource
{
public partial class Layout
{
public const int Pi = 2130903040;
...
}
...
}
The generated field matches the filename
UI Creation
v The Activity.SetContentView method instantiates all the Views in a
layout file and loads them as the Activity's UI
Call from
OnCreate
[Activity(MainLauncher = true)]
public class PiActivity : Activity
{
protected override void OnCreate(Bundle
bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Pi)
} ;
...
}
Pass the resource identifier of the layout file
What is an Id?
v The View class defines an Id property that is used to uniquely identify an
instance of a View
namespace Android.Views
{
public class View
{
public virtual int Id { get; set; }
...
}
}
Notice that the type is int, not string
How to set an Id
v Set the Id of a View in XML using the id attribute and the syntax @+id
Set an id in the XML
<EditText android: id="@+id/digitsInput" ... />
Build tool generates
a integer field and
loads the integer
into the View's Id
public partial class Resource
{
public partial class Id
{
public const int digitsInput = 2131034113;
...
}
...
}
Resource.designer.cs
How to access views from code
v Use Activity.FindViewById to lookup a View in an Activity's UI
[Activity(MainLauncher = true)]
public class PiActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Pi);
var et = FindViewById<EditText>(Resource.Id.digitsInput);
...
}
...
}
Update your Android SDK
Tasks
1.
2.
3.
4.
Review native Android development
Understand the Xamarin.Android
development process
Update your Android Tools
Update your Android Platform SDK
Motivation
v
Xamarin.Android uses native Android tools and libraries
Xamarin Android
JDK
(Java SDK)
Android
SDK
Android
NDK
You need to install updates to
target new Android versions
Mono
.NET
What is the JDK?
v
The Java SDK (JDK) is the collection of libraries and tools needed to build
and run Java applications
java.*
library
packages
Dev tools
Runtime
(compiler,
jarsigner, etc.)
(virtualmachine
and libraries)
These tools are used in
the Android build process
Docs and
Samples
Library
source code
What is the Android SDK?
v
The Android SDK contains the APIs and tools needed to create and run a
native Android app
SDK
Platform
Core libraries:
the java.* and
android.* types
Google APIs
(e.g. calendar,
gmail access)
Optional
libraries
Tools
SDK
Docs and
Samples
Build tools (e.g. bytecode
compiler) and runtime
support (e.g. debug tools)
Emulator
images
What is the Android NDK?
v
The Android NDK is a collection of code and tools that let you write part of
your native Android app in a language like C and C++
C
Headers
Compilers
and linkers
(e.g. create
native ARM
binaries)
Tools
(e.g. addnative
binaries to an
.apk)
NDK
Docs and
Samples
Writing part of your app in C/C++ is rare. It will increase complexity but may not increase
performance. It can be useful in games or to reuse an existing C/C++ codebase.
What is Mono?
v
Mono is an open-source implementation of the .NET Framework; several
parts are used in Xamarin.Android development
Base Class
Library
Mono Class
Library
Mono
Runtime
C# Compiler
Many of these
are available in
Xamarin.Android
Not
used
Used to
execute
your IL
Used to
compile
your C#
Native compilation
v
Java source is compiled into Dalvik bytecodes for deployment (bytecodes
are analogous to .NET Intermediate Language)
Java
compiler
Android dex
compiler
Java bytecodes
.dex files
Dalvik bytecodes
Native packaging
v
An app's bytecodes, images, data files, etc. are combined into an
Application Package (.apkfile) for deployment
.dex files
Resources
(e.g. images)
Android
apkbuilder
.apk file
The .apk file contains
all the app's assets
and is ready to run
For upload to the Play store, there are two more steps that are not shown: signing with
jarsigner and optimizing the layout of the file with zipalign.
Native execution
v
The Android Runtime (ART) is the execution engine for Android apps
MyApp.apk
Android
Runtime
(ART)
Apps run in their own process
with their own copy of the
ART Virtual Machine
Bytecodes are compiled to
native code at installation
(called Ahead-of-Time or AOT)
Android versions before 5.0 used the Dalvik VM which did runtime bytecode translation.
Xamarin.Android compilation
v
C# code in Xamarin.Android apps is compiled to .NET Intermediate
Language (IL)
C# compiler
assembly
IL and metadata
Xamarin.Android linking
v
The Xamarin.Android linker removes unused IL to reduce the size of your
app for deployment
Mono assemblies
Linker
your assemblies
Mono assemblies
(filtered)
your assemblies
(filtered)
Determines which class members are used in your
app and includes only those members in the output
Project settings and code Attributes let you control which assemblies are linked.
Dynamic code should not use the linker (e.g. members accessed via reflection).
Xamarin.Android and the Mono VM
v
Xamarin.Android apps have the Mono Runtime packaged in their .apk file
because it is needed to execute IL
Mono
Runtime
The Xamarin build tools
add the Mono VM to
your application package
Android
apkbuilder
.apk file
Xamarin.Android execution
v
Mono and ART VMs run side-by-side to execute a Xamarin.Android app
your
C# code
.NET
libraries
Mono
Runtime
java.*
libraries
android.*
libraries
Android
Runtime (ART)
Linux Kernel
Xamarin.Android installation
v
The Xamarin unified installer (http://xamarin.com/download) loads nearly
everything you need to develop and run Xamarin.Android apps
JDK
(Java SDK)
Android
SDK
Android
NDK
Android requirements
Xamarin
Studio
Xamarin
Android
Xamarin requirements
(including Mono items)
Android SDK updates
v
You need to manually update your Android SDK Platform and Tools so you
can build against the latest versions of Android
Android SDK
SDK
Platform
Google APIs
(e.g. calendar,
gmail access)
Supplies the java.* and
android.* library types
that you code against
Tools
SDK
Docs and
Samples
Supplies the build tools
and runtime support tools
need for dev and execution
Emulator
images
Android versions
v
Android versions are identified via a code name and two numbers
Code Name
Version
API Level
Marshmallow
6.0
23
Lollipop
5.1
22
Lollipop
5.0
21
Kit Kat (watch)
4.4W
20
Kit Kat
4.4
19
Jelly Bean
4.3
18
Jelly Bean
4.2.2
17
Jelly Bean
4.2
17
...
...
...
Level identifies the
combination of libraries,
manifest elements,
permissions, etc. that you
code against as a developer
What is Android SDK Manager?
v
The Android SDK Manager is a tool from Google that lets you install new
(and old) versions of the Android SDK
SDK
Platform
Google APIs
(e.g. calendar,
gmail access)
Tools
SDK
Docs and
Samples
Emulator
images
The SDK Manager lets you install all of these components
How to launch Android SDK Manager
v
Xamarin Studio and Visual Studio menu entries launch the Android SDK
Manager
Xamarin Studio Tools menu
Visual Studio Tools > Android menu
Updating tools
v
Android splits the SDK tools into three parts that can be updated
separately; you should keep all three categories up-to-date
Update all of these.
The SDK manager
tells you when
updates are ready.
Updating platform versions
v Use the SDK Manager to install the
platform versions you would like to
compile against
Install the SDK Platform
for the versions you need
Summary
1.
2.
3.
4.
Review native Android development
Understand the Xamarin.Android
development process
Update your Android Tools
Update your Android Platform SDK
AND102
Activities and Intents
Objectives
1.
2.
3.
4.
5.
Start an Activity in your .apk
Finish an Activity
Pass arguments to an Activity
Get Activity results
Start a system Activity
Motivation
An Android app is a collection of collaborating Activities; it is common
for one Activity to start another Activity from the same .apk
MyApp.apk
Activity 1
Activity 2
Start
Activity 3
Data files,
images, etc.
Group Exercise
Explore the completed lab exercise
Activity-start overview
Request packaged
inside an Intent
Context
Context
Activity 1
Activity 2
Intent
The request goes
through a Context
Start
You need to use a few different Android types to start an Activity
Android OS
The OS starts the
new Activity
What is a Context?
Context is an access point to the Android environment running your app
Context
Activity
OS services
Android OS
MyApp.apk
Info about your app
In-package
files
Resources and assets
On-device
files
Runtime file system
Activity is-a Context
The Activity class inherits from
Context
This ensures each Activity has
access to the environment for
loading resources and interacting
with Android
Context
ContextWrapper
(proxy implementation pattern)
ContextThemeWrapper
(support for styles/themes)
Activity
What is an Intent?
An Intent is a request you send to Android to start a new Activity
MyApp.apk
Activity 2
Intent
Start
Activity 1
Activity 3
Data files,
images, etc.
Android starts the Activity for you
Android OS
What is an explicit Intent?
An explicit Intent is an Intent that exactly identifies the Activity to start
public class Intent : ...
{
public Intent(Context packageContext, Type
type) { ... }
...
}
This must be a Context associated
with the .apk containing the target
Activity (use your current Activity
when they are from the same .apk)
Type object uniquely
identifies the target Activity
Start methods
Context provides the core methods for starting Activities
Start
Convenience
method
public abstract class Context : ...
{ ...
public abstract void StartActivity(Intent intent);
public void StartActivity(Type type);
}
Context and Activity provide other methods to start an Activity; however, the ones
shown here are among the most common.
How to start an Activity
To start a new Activity, create an Intent and pass it to StartActivity
Common to
start in response
to a user action
public class Activity1 : Activity
{ ...
void OnClick(object sender, EventArgs e)
{
var intent = new Intent(this, typeof(Activity2));
Start
base.StartActivity(intent);
}
}
Finish an Activity
Tasks
1.
2.
3.
Understand Stack Navigation
See the behavior of the Backbutton
Programmatically finish an Activity
Motivation
You need to know how to programmatically finish an Activity to
implement functionality like "cancel"
The "Add new contact"
Activity has a cancel button
What is navigation?
Navigation describes the paths you create in your app to let the user
switch between your various Activities
Touch a contact
to move to the
details screen
What is the Back button?
Android devices have a Back Button that returns the user to the previous
Activity
The Contacts app lets
users move from the
All Contacts screen
to view an individual
contact and then back
Navigation patterns
Android apps use several common navigation patterns
Stack
Tab
Drawer
This course discusses stack navigation; our navigation course covers other patterns.
What is stack navigation?
Stack navigation records the sequence of Activities in a stack to enable
the user to return from any Activity to the one that started it
What is the back-stack?
The back-stack is a historical record of the user's live Activities
Activity 1
Activity 2
Activity 3
Back stack
Activity 3
Activity 2
Activity 1
Back-stack scope
The Activities in the back-stack may span multiple apps
Contact
Phone
Back stack
Phone
Contact
Stack contains Activities
from Contacts and Phone
Back-stack push
Android pushes Activities onto the back-stack automatically when you
start them
Back stack
public class Activity1 : Activity
{ ...
void OnClick(object sender, EventArgs
e)
Activity 2
{
Activity 1
base.StartActivity(typeof(Activity2))
;
}
Started Activities go on the stack
}
Automatic back-navigation
The Back-button automatically pops the back-stack and returns the user
to the previous Activity
Activity 1
Activity 2
Back stack
Activity 2
Activity 1
Programmatic back-navigation
Activity provides a Finish method that ends the current Activity and
returns to the previous Activity on the back-stack
Ends the
current
Activity
public class Activity : ...
{ ...
public virtual void Finish();
}
When to call Finish?
An Activity can call Finish in cases when the behavior of the Back
Button might be unclear to the user
E.g. add a "cancel"
button to your UI
so the user can be
sure their changes
will not be saved.
public class Activity2 : Activity
{ ...
void OnCancelClick(object sender, EventArgs e)
{
base.Finish();
}
}
Pass arguments to an Activity
Tasks
1.
2.
Load a Bundle of arguments into
an Intent
Retrieve the arguments in the
target Activity
Motivation
Activities typically need to pass data between them
Pass an Id so the
details view knows
which contact to
display
App process
Each app runs in its own process
The Contacts and
Phone apps run in
separate processes
even when they
work together
Activity process
Each Activity runs in its app's process (i.e. the process associated with
the app of which it is a part)
Contacts app process
Phone app process
Arguments and processes
Only simple types and serialized objects can move between Activities;
object references cannot since they can't cross process boundaries
The contact's information
moves between processes
What is a Bundle?
A Bundle is a collection of key ➡ value pairs passed between Activities
Name Ann
Phone202-555-1212
Type Mobile
Keys are strings,
Values are limited
to a few types
Bundle and simple types
Bundle has put/get methods for the simple types
Supports integer types,
floating point types,
Boolean, character,
and string
Also supports arrays
and lists of the simple
types (not shown)
public sealed class Bundle : ...
{
public void
PutInt
(string key, int
public int
GetInt
(string key, int
value);
defaultValue);
public void
PutDouble(string key, double value);
public double GetDouble(string key, double defaultValue);
public void
PutString(string key, string value);
public string GetString(string key, string defaultValue);
...
}
Bundle and complex types
Bundle supports two ways to serialize complex objects:
Android.OS.IParcelable and Java.IO.ISerializable
Objects must
be serialized
to be stored
in a Bundle
public sealed class Bundle : ...
{
public void
PutParcelable(string key, IParcelable value);
public Object GetParcelable(string key);
public void
PutSerializable(string key, ISerializable value);
public ISerializable GetSerializable(string key);
...
}
Xamarin has samples for how to implement both interfaces:
https://github.com/xamarin/monodroid-samples/blob/master/ExportAttribute/ExportAttributeTest/MainActivity.cs
What are Intent Extras?
Extras are a Bundle inside an Intent to be passed between Activities
Intent
Name Ann
Phone202-555-1212
Type Mobile
The Extras
Bundle inside
an Intent
Intent access in the Target
The starting Intent is available in the Target's Intent property
Intent
Name Ann
Phone202-555-1212
Type Mobile
This Intent and its
Extras are available here
How to load Intent Extras
There are two equivalent ways to load Intent Extras
Explicit
creation
Convenience
methods
var bundle = new Bundle();
bundle.PutInt("ContactId", 123456789);
var intent = new Intent();
intent. PutExtras(bundle);
var intent = new Intent();
intent.PutExtra("ContactId", 123456789);
How to retrieve Intent Extras
There are two equivalent ways to retrieve Intent Extras in the Target
Explicit
access
Convenience
methods
int id = base.Intent .Extras.GetInt("ContactId", -1);
int id = base.Intent .GetIntExtra("ContactId", -1);
Default value to be returned if key not found
Get Activity results
Motivation
An Activity often provides a service for another Activity and needs to
report the results
Intent
Source
Activity
Item Name
Item Count
Add Item
Activity
The values entered by the user are returned
Data-flow overview
Source and Target Activities pass several pieces of data between them
Source
Activity
Intent Extras
Request Code
Request Code
Result Code
Intent Extras
Target
Activity
Method overview
Source and target Activities use Activity methods to pass data
You call StartActivityForResult
Source
Activity
Target
Activity
You call SetResult
Android calls OnActivityResult
What is a request code?
A request code is an integer you pass to an Activity to help you identify
it; you get that same value back when the Activity finishes
Source
Activity
Request Code = 100
Request Code = 200
The values are completely your choice,
they have no intrinsic meaning
Target
Activity 1
Target
Activity 2
Request code purpose
All Activities report results via the same method in the Source; the
request code is returned with the results to identify the Target
Source
Activity
Intent Extras
Request Code = 100
Request Code = 100
Result Code
Intent Extras
Target
Activity 1
Lets you determine these results are from Activity 1
How to pass a request code
Use StartActivityForResult to start an Activity and pass it a
request code
public class Activity : ...
{
public virtual void StartActivityForResult(Intent intent, int requestCode);
}
You call this in your Source Activity
Identifies the Target Activity
to start and carries a Bundle
of arguments if needed
Your choice of
request code to let
you track the Target
What is a Result code?
A result code is an enum that an Activity uses to indicate success/failure
Source
Activity
Intent Extras
Request Code = 100
Request Code = 100
Result Code = Ok
Intent Extras
Target
Activity 1
Has three possible
values: Ok,
Canceled, and
FirstUser
FirstUser indicates the first integer value available for user-defined result codes (i.e. all
predefined members have values less than FirstUser).
Result data
An Activity can return a Bundle to the Activity that started it
Source
Activity
Intent Extras
Request Code = 100
Request Code = 100
Result Code
Intent Extras
Target
Activity 1
You create an Intent and a Bundle, then load the Bundle with data
How to report results
The Target Activity uses SetResult to specify what to return to the
Source
public class Activity : ...
{ ...
public void SetResult(Result resultCode);
public void SetResult(Result resultCode, Intent data);
}
Target can report just a result code or a result code + data
How to retrieve results
The Source Activity overrides OnActivityResult to receive results
public class SourceActivity : ...
{ ...
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (resultCode == Result.Ok && requestCode == 100)
{
string name = data.GetStringExtra("ItemName");
int
count = data.GetIntExtra
("ItemCount", 0);
...
}
}
}
Data returned by the Target Activity
The Intent loaded by the Target Activity
Launch a system Activity
Tasks
1.
2.
3.
Create an implicit Intent
Load Intent Action, Data, and
Extras
Verify that Android found an
Activity that matches your implicit
Intent
Motivation
You can utilize Android Activities like Contacts, Phone, Camera, etc.
E.g. your app
could let the
user call your
sales team or
help line
My
Activity
Intent
External collaboration
You can start an Activity from a different .apk or one installed as part of
a standard Android app
Standard Android
Intent
Intent
Activity 2
Phone Dialer
Activity
Launch
Activity 1
Other.apk
Launch
MyApp.apk
Android OS
What is an implicit Intent?
An implicit Intent describes what you want done without specifying
which Activity should do it
Activity 1
Activity 2
In tent
1. Android looks at the info
you loaded into the Intent
?
2. Android chooses an
Activity for you
Android OS
Activity 3
?
Implicit Intent payload
You load several pieces of information into an Implicit Intent that
describe the operation you need performed
Activity 1
In tent
The Intent can contain:
• Action
• Data
• MIME Type
• Categories
• Extras
Android OS
How to know what to provide?
The Android documentation tells you what to load into an Intent
Activity 1
Intent
1. Read the documentation
2. Build a matching Intent
How to create Intents for many common cases is described here:
https://developer.android.com/guide/components/intents-common.html
What is an Intent Action?
An Intent Action specifies the type of work you need done
"Display some info"
"Dial the phone"
"Send a message"
Action specification
Actions are specified using strings; the Intent class has a predefined
string for many common Actions
Symbolic constant
Value
Meaning
Intent.ActionView
android.intent.action.VIEW
Show some info to the user
Intent.ActionDial
android.intent.action.DIAL
Dial the phone
Intent.ActionEdit
android.intent.action.EDIT
Let the user edit some data
Intent.ActionSendto
android.intent.action.SENDTO
Send a message
...
...
...
Some Action constants are packaged with the classes they are associated with. For
example, you use MediaStore.ActionImageCapture to take a photo.
How to set the Action
You can set an Intent's Action with either the constructor or the
SetAction method
var intent = new Intent();
intent.SetAction(Intent.ActionView);
Action is a string, typical to use the predefined constants
What is Intent Data?
Intent Data is a single piece of information for use by the Target Activity
Data for a map Activity
Data for a phone dialer Activity
Data for a browser Activity
geo:37.797776,-122.401881?z=16
tel:(855) 926-2746
http://www.xamarin.com
The Android documentation will generally tell you what to use for the Data
How to set the Data
Use the SetData method to load Data into an Intent
var intent = new Intent();
...
intent.SetData(Android.Net.Uri.Parse("http://www.xamarin.com"));
Data is an Android URI
What is Intent MIME Type?
The MIME Type indicates the type of the Data you want the Intent to
manipulate, it helps Android determine which Activity to launch
Insert a new contact
Add a calendar event
Select an image
vnd.android.cursor.dir/contact
vnd.android.cursor.dir/event
image/*
The Android documentation will generally tell you what to use for the MIME Type
How to set the MIME Type
Use the SetType method to set the MIME Type
var intent = new Intent();
...
intent.SetType("image/jpeg");
Specify you want an Activity
that can work with jpeg images
What is an Intent Category?
A Category restricts the kind of Activity you would like to handle your
Intent
Preference
(i.e. settings
panel)
Tab
(i.e. intended to
live inside a tab)
Openable
(i.e. picker)
You will not need to use Categories to launch most common Activities.
How to add a Category
Use the AddCategory method to add one or more Categories
var intent = new Intent();
...
intent.AddCategory(Intent.CategoryPreference);
The Intent class has constants
for the standard Categories
Extras specification
Extras are specified using strings; a few predefined strings are in the
Intent class but most are packaged in the classes they work with
Symbolic constant
Value
Meaning
Intent.ExtraEmail
android.intent.extra.EMAIL
List of addresses for an email
MediaStore.ExtraOutput
output
Location for camera to save
AlarmClock.ExtraRingtone
android.intent.extra.alarm.RINGTONE
Tone to play for an alarm
EventsColumns.Title
title
Calendar event title
...
...
...
Example: show a location on a map
Use an implicit Intent with ActionView to show a map location
var intent = new Intent();
intent.SetAction(Intent.ActionView);
intent.SetData(Android.Net.Uri.Parse("geo:37.797776,-122.401881?z=16"));
Latitude
Longitude
Zoom level
This requires a mapping app to run. Use an emulator with the Google APIs installed.
Example: send an email
Use an implicit Intent with ActionSendto to send an email
var intent = new Intent();
intent.SetAction(Intent.ActionSendto);
// tell Android to use only email apps to service this request
intent.SetData(Android.Net.Uri.Parse("mailto:"));
intent.PutExtra(Intent.ExtraEmail, new string[] { "[email protected]" });
intent.PutExtra(Intent.ExtraSubject, "How are you?");
The Extras support all common fields like To, CC, Subject, etc.
Error checking
To avoid a runtime exception, you should verify that your implicit Intent
is valid before calling StartActivity
var intent = new Intent();
...
if (intent.ResolveActivity(PackageManager) != null)
{
StartActivity(intent);
}
Test if Android found
a matching Activity
The Package Manager knows all Activities
installed on the device. Your Activity
inherited this property from Activity.
Summary
1.
2.
3.
Create an implicit Intent
Load Intent Action, Data, and
Extras
Verify that Android found an
Activity that matches your implicit
Intent
Thank You!
Please complete the class survey in your profile:
university.xamarin.com/profile