An Intent
is an object used to specify the transition from one android activity to another.
You can create a second activity in your project by right-clicking on the package name (such as com.example.app
) under src/main/java
, and selecting New » Activity. Suppose our new activity is called SecondActivity
.
To initiate a transition from the MainActivity
to the SecondActivity
(perhaps in response to a button click), you can enter this code:
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
The getActivity()
works if this code is somewhere within the inner Fragment
class. If instead you are doing this directly in the Activity
class, you can replace it with this
:
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
In the above example, we transitioned to an explicit activity, indicated by SecondActivity.class
. In other cases, we may avoid specifying a particular activity and instead let the Android system (and perhaps the user) decide which activity to open.
For example, suppose I want to link to a map view of some location on the Earth, specified by latitude and longitude. In that case, we specify that we want to VIEW a geo:
URL:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:0,0?q=20.629595,-87.069032(Playa)"));
startActivity(intent);
The format of this URL is geo:0,0?q=LATITUDE,LONGITUDE(LABEL)
. When I click the button to activate this intent, my phone has two applications that handle geo URLs, as shown in the screen-shot.
On my tablet, I don’t have VZ Navigator, but instead I have Google Earth, so it still offers me a choice. The user can select an app and then “Always” so that this association is used as the default in the future.
A similar thing happens with YouTube URLs. This Intent transitions to a YouTube video:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v=Yexc19j3TjE"));
startActivity(intent);
My phone has three ways to visit a YouTube URL, as shown in the screen-shots.
For a ton of extra information about how Android (and perhaps the user) is choosing the target activity, you can set a flag before starting the activity, like this:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v=Yexc19j3TjE"));
intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
startActivity(intent);
and then it will dump the details into the system log. Search for the tag IntentResolver
to find them.