Tutorial 3 – Android Basic
Navigation
CSCI 3310
Mobile Computing and Application Development
ZAITANG LI
This work is licensed under a Creative Commons
This note is partly based on the Google Developers Training - Android Developer Attribution 4.0 International License.
Fundamentals V2 Slides share under CC Attribution
Contents
● Activities
● Defining an Activity
● Starting a new Activity with an Intent
● Passing data between activities with extras
● Navigating between activities
2
Activities
(high-level view)
3
What is an Activity?
● An Activity is an application component
● Represents one window, one hierarchy of views
● Typically fills the screen, but can be embedded in other Activity or a
appear as floating window
● Java class, typically one Activity in one file
4
What does an Activity do?
● Represents an activity, such as ordering groceries, sending email, or
getting directions
● Handles user interactions, such as button clicks, text entry, or login
verification
● Can start other activities in the same or other apps
● Has a life cycle—is created, started, runs, is paused, resumed, stopped,
and destroyed
5
Examples of activities
6
Apps and activities
● Activities are loosely tied together to make up an app
● First Activity user sees is typically called "main activity"
● Activities can be organized in parent-child relationships in the Android
manifest to aid navigation
7
Layouts and Activities
● An Activity typically has a UI layout
● Layout is usually defined in one or more XML files
● Activity "inflates" layout as part of being created
8
Implementing
Activities
9
Implement new activities
1. Define layout in XML
2. Define Activity Java class
○ extends AppCompatActivity
3. Connect Activity with Layout
○ Set content view in onCreate()
4. Declare Activity in the Android manifest
10
1. Define layout in XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Shop for Food!" />
</RelativeLayout>
11
2. Define Activity Java class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
}
}
12
3. Connect activity with layout
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
} Resource is layout in this XML file
13
4. Declare activity in Android manifest
<activity android:name=".MainActivity">
14
4. Declare main activity in manifest
MainActivity needs to include intent-filter to start from launcher
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
15
Intents
16
What is an intent?
An Intent is a description of an operation to be performed.
An Intent is an object used to request an action from another app
component via the Android system.
Originator App component
Intent Action
Android
System
17
What can intents do?
● Start an Activity
○ A button click starts a new Activity for text entry
○ Clicking Share opens an app that allows you to post a photo
● Start an Service
○ Initiate downloading a file in the background
● Deliver Broadcast
○ The system informs everybody that the phone is now charging
18
Explicit and implicit intents
Explicit Intent
● Starts a specific Activity
○ Request tea with milk delivered by Nikita
○ Main activity starts the ViewShoppingCart Activity
Implicit Intent
● Asks system to find an Activity that can handle this request
○ Find an open store that sells green tea
○ Clicking Share opens a chooser with a list of apps
19
Starting Activities
20
Start an Activity with an explicit intent
To start a specific Activity, use an explicit Intent
1. Create an Intent
Intent intent = new Intent(this, [Link]);
2. Use the Intent to start the Activity
startActivity(intent);
21
Start an Activity with implicit intent
To ask Android to find an Activity to handle your request, use an implicit
Intent
1. Create an Intent
Intent intent = new Intent(action, uri); // Universal
Resource Identifier
2. Use the Intent to start the Activity
startActivity(intent);
22
Implicit Intents - Examples
Show a web page
Uri uri = [Link]("[Link]
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = [Link]("[Link]
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
23
How Activities Run
● All Activity instances are managed by the Android runtime
● Started by an "Intent", a message to the Android runtime to run an
activity
User clicks MainActivity FoodListActivity OrderActivity
launcher icon What do you want to do? Choose food items...Next Place order
Intent: Start Start Intent: Start chooseIntent: Start finish
app Android main Shop Android food activityorder Android order activity
System System System
activity
24
Sending and
Receiving Data
25
Two types of sending data with intents
● Data—one piece of information whose data location can be
represented by an URI
● Extras—one or more pieces of information as a collection of key-
value pairs in a Bundle
26
Sending and retrieving data
In the first (sending) Activity:
1. Create the Intent object
2. Put data or extras into that Intent
3. Start the new Activity with startActivity()
In the second (receiving) Activity:
1. Get the Intent object, the Activity was started with
2. Retrieve the data or extras from the Intent object
27
Putting a URI as intent data
// A web page URL
[Link](
[Link]("[Link]
// a Sample file URI
[Link](
[Link](new File("/sdcard/[Link]")));
28
Put information into intent extras
Option 1
putExtra(String name, int value)
[Link]("level", 406);
Option 2
putExtra(String name, String[] value)
String[] foodList = {"Rice", "Beans", "Fruit"};
[Link]("food", foodList);
Option 3
putExtras(bundle);
⇒ if lots of data, first create a bundle and pass the bundle.
● See documentation for all
29
Sending data to an activity with extras
public static final String EXTRA_MESSAGE_KEY =
"[Link]";
Intent intent = new Intent(this, [Link]);
String message = "Hello Activity!";
[Link](EXTRA_MESSAGE_KEY, message);
startActivity(intent);
30
Get data from intents
Intent intent = getIntent();
Option 1
getData();
Uri locationUri = [Link]();
Option 2
int getIntExtra (String name, int defaultValue)
int level = [Link]("level", 0);
Option 3
Bundle bundle = [Link]();
⇒ Get all the data at once as a bundle.
● See documentation for all
31
Returning data to the starting activity
1. Use startActivityForResult() to start the second Activity
2. To return data from the second Activity:
● Create a new Intent
● Put the response data in the Intent using putExtra()
● Set the result to Activity.RESULT_OK
or RESULT_CANCELED, if the user cancelled out
● call finish() to close the Activity
1. Implement onActivityResult() in first Activity
32
startActivityForResult()
startActivityForResult(intent, requestCode);
● Starts Activity (intent), assigns it identifier (requestCode)
● Returns data via Intent extras
● When done, pop stack, return to previous Activity, and execute
onActivityResult() callback to process returned data
● Use requestCode to identify which Activity has "returned"
33
1. startActivityForResult() Example
public static final int CHOOSE_FOOD_REQUEST = 1;
Intent intent = new Intent(this,
[Link]);
startActivityForResult(intent, CHOOSE_FOOD_REQUEST);
34
2. Return data and finish second activity
// Create an intent
Intent replyIntent = new Intent();
// Put the data to return into the extra
[Link](EXTRA_REPLY, reply);
// Set the activity's result to RESULT_OK
setResult(RESULT_OK, replyIntent);
// Finish the current activity
finish();
35
3. Implement onActivityResult()
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
[Link](requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) { // Identify activity
if (resultCode == RESULT_OK) { // Activity succeeded
String reply =
[Link](SecondActivity.EXTRA_REPLY);
// … do something with the data
}}}
36