Android Development — Part 5
Connection between activities
Activity is a single layout of an app. In an app their are usually more than one activity , the connection between these activities are based on a task description represented by an Intent
object. Intents are asynchronous messages which allow application components to request functionality from other Android components. Intents allow you to interact with components from the same applications as well as with components contributed by other applications. For example, an activity can start an external activity for taking a picture. Intents are objects of the android.content.Intent
type. In Android the reuse of other application components is a concept known as task. An application can access other Android components to achieve a task.
Given code demonstrate the use on intent
Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);
Intents are of two category:-
- Implicit Intents
- Explicit Intents
Implicit Intents :- Implicit Intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. or use implicit intents if you don’t care which app component handles the intent as long as they can. For example, if you want to access camera in your Facebook.
Testing implicit intents:-
Like in previous blog use either OnClickListener or onClick method and add following lines of code.The code below opens google.com in a browser.
public void onClickButton(View v){
String url = "http://www.google.com";
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
Explicit Intents:- An implicit intent specifies an action that can invoke any app on the device able to perform the action. Or if you know exactly which app component should handle your intent.For example using multi screen with in android app.
For this create a new activity in your project file. Reference to create a new activity. And name your new activity ChildActivity (for now). Similarly, create onClick method.
Open MainActivity.java write following lines of code.
public void onClickButton(View v){
Context context = MainActivity.this;
Class destinationActivity = ChildActivity.class;
Intent intent = new Intent(context, destinationActivity);
startActivity(intent);
}
With this code when button is clicked MainActivity is switched to ChildActivity.
And in AndroidMainfest.xml you will see code of line added after creating new activity.
<activity android:name=”.ChildActivity”></activity>
To check if this Activity is working cut<intent-filter> from MainActivity as
<activity android:name=".ChildActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
For more information do check http://www.vogella.com/tutorials/AndroidIntent/article.html.