working with multiple activities - washington and...
TRANSCRIPT
Introduction
Working with multiple activities
Putting together the AndroidManifest.xml file
Creating multiple views
Introduction to intents
Passing data to activities
Multiple Activities (Introduction)
When the user switches between activities, one activity is stopped, and the other is started
Remember the activity lifecycle
Note that you can start activities that belong to other applications
A Web Browser for example
A mailer
A dialer
Starting an Activity
To start a new activity, your current actvitycalls startActivity() passing an Intent
as the argument
The Intent describes the activity that you
want to start
The user can then select from the possible intents (external)
Or the activity just runs (external)
An activity can also return results
Creating a Second Activity
Remember that an activity is just a class
So we just
Add a new class
Inherit from android.app.Activity
Add the activity to the manifest
Nowadays this is mostly automated via Android Studio’s New Activity Wizard.
Let’s look at the old-fashioned way of doing it …
Introduction to Intents
Before we can explicitly start an activity, you need to understand intents
An intent is an object used to communicate with the OS
Intents are used with activities, services, broadcast receivers, and content providers
We have only discussed activities so far
You can use intents to tell the Android OS which activity to start
Intents (Philosophically)
As the name implies, it’s an intention to do an action
It’s a message to say
I did something
I want something to happen
When you create an intent, you are saying that you want to move from one activity to another
Intents (Types)
There are two types of intents, confusingly named:
Explicit intents are used with a Context and Class object to start an activity within your application
Implicit intents are used to start activities outside of your application
There is much more to intents than discussed here
Creating an Implicit Intent
On overloaded version of the Intent constructor accepts an action
Intent.ACTION_VIEW is a generalized intent
The application is inferred based on the data passed when the activity is started
Intent.ACTION_CALL starts the default dialer
Creating an Implicit Intent (Example)
Create an implicit intent and pass a URL to the intent
String url = "http://www.wlu.edu";
Intent i = new
Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Intent (Constructor)
This is but one of the many constructors
The first argument contains the current activity
The second argument contains the class name of the activity to be started
Intent (Creating)
The following appears in the current activity (MainActivity.this) and starts the second activity (Page2Activity.class)
What’s weird about this
Two somewhat unusual things we’re doing here:
Gives us the current object instantiating ourMainActivity class:
why can’t we just use this by itself?
Because our code here is inside a method of another (anonymous inner) class, this would be an instance of that
class, not the desired instance of MainActivity.
public class MainActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
myButton = (Button)findViewById(R.id.my_button);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startNewActivityOpen =
new Intent(MainActivity.this, Page2Activity.class);
}});
What’s weird about this
Two somewhat unusual things we’re doing here:
Recall our discussion of reflection: here, we explicitly refer to the class that our Page2Activity will instantiate, rather than instantiating it ourselves with new. The OS will
take care of that for us when we call startNewActivity.
Starting an Activity (Illustration)
startActivity is called with an Intent. The
ActivityManager uses that intent to determine the activity to start
Passing Data to Activities
You can pass data from one activity to anther through intent extras
Extras are just arbitrary data that can be passed to an intent
An extra is a key / value pair that is passed to an intent
The started activity can read this extra data
Creating (Writing) an Extra
First, create the Intent as shown before
Second, call putExtra()
First argument contains the key
Second argument contains the value
What does this remind us of?
Creating (Writing) an Extra
The first argument contains the key, which here is a constant “LastActivity”
The second contains the value “MainActivity”
Reading an Extra
The getIntent() method returns an Intent object
Its methods get values of a particular type
getBooleanExtra(), getByteExtra(), getIntExtra(), etc…
Reading and Writing Instance Data (1)
By default, the system uses the Bundle
instance to save information about each View object
Layout state information is restored automatically
You are responsible for saving and restoring other instance data
Note that a rotation causes the application to be destroyed and recreated with a new layout (later)
Reading and Writing Instance Data (2)
To save additional instance data, override the onSaveInstanceState() callback method
To restore the saved instance data, override the onRestoreInstanceState() callback
method
onSaveInstanceState()
Call putInt() (or other type) to save data
The first argument contains the key
The second argument contains the value
onRestoreInstanceState()
Call getInt() (or other type) to restore
data.
The first argument contains the key
The method returns the value
Intent Extras vs. Saved Instance State
Intents are used to pass data between activities; Saved Instance States are used by an activity to save/restore its previous state when we switch to/from another activity.
Both make use of the Bundle class (explicitly
or implicitly), but it’s how they do it that distinguishes them ….
Intent Extra: like a Python dictionary
Two arguments: first is key string (like Python), second is anything we like (again, like Python)
Saved Instance State: Methods supporting explicit types
Again, first argument is key string, but second must agree with specific put/get
method; e.g.,@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(IS_CHEATER, mIsCheater);
savedInstanceState.putBooleanArray(CHEATED_ON_QUESTIONS,
mCheatedOnQuestions);
}
This makes sense, because we use these methods to save / restore the typed instance variables of the Activity subclass.
Returning an Activity Result (Introduction)
There are times when we need to return a result from an activity
We start an activity as before; however, we pass a request code when starting the activity
The request code is an integer
It is sent to the child (started) activity
The result is then returned to the parent
Returning an Activity Result
Call startActivityForResult() instead of startActivity()
The first argument contains the intent
The second argument contains the integer result that will be returned
The result is returned through overriding onActivityResult() in the parent activity
Returning an Activity Result
To return the result, you call one of two forms of setResult()
The first returns a result code
Typically
Activity.RESULT_CANCELED
Activity.RESULT_OK
The second returns the result code and intent data
Call finish() to return from the activity
Activity Result Example (1)
Start the activity as before with startActivity except call startActivityForResult
The first argument contains the activity as before
The second argument contains an integer request code
It answers the question from the activity from which we are returning
Activity Result Example (1)
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent =
new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
Activity Result Example (2)
Here we return a code but no data
The intent is empty and has no extras
RESULT_CANCELED is an Android constant
We call finish to return to the calling Activity
Activity Result Example (2a)
Here we return a code and data
The Intent has extra data
We change the return code
Activity Result Example (3)
In the calling activity, handle the onActivityResult() event, using the
request code to determine which other activity is giving us the result:
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding toif (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successfulif (resultCode == RESULT_OK) {
// The user picked a contact.// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)}
}}
AndroidManifest.xml (Multiple Activities)
The AndroidManifest.xml must list all of the activities
Remember one activity is designated as the launcher activity
Implicit Activities (Introduction)
Implicit activities are handled outside of your application
They are other registered applications
Your browser, mailer, or dialer
Creating an Implicit Intent
Creating an implicit intent is a two step process.
Create an intent with an argument describing the intent category
Intent.ACTION_VIEW is a generalized intent
commonly used to process URLS
Intent.ACTION_CALL invokes a dailoger
On the Intent, Call the setData method to
pass the url
Call startActivity as usual