android intent example

In this post we are going to make an example that demonstrate the use of intent, intent filter and startActivity in android.
Create a new android application project in eclipse and name it as IntentDemo. I change the activity name as First_Activity and corresponding layout name as first_layout.
Ads by Google


Place a button on the first_layout.xml file as shown bellow.
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".First_Activity" >
<Button
android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="51dp"
android:text="Go TO SECOND ACTIVITY" />
</RelativeLayout>

Now create a new Activity with class name  Second_Activity.java and layout name second_layout.xml.
Open the AndroidManifest.xml file and add the following code within the application tag.

 <activity  
android:name=".Second_Activity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="second_filter" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>

Create an object of the intent in First_Activity.java file and start the second activity using startActivity method.

                     Intent i = new Intent("second_filter");  
startActivity(i);

Finalized code for First_Activity.java is given bellow.

 package com.intentdemo;  
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class First_Activity extends Activity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
button = (Button)findViewById(R.id.bn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent("second_filter");
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_, menu);
return true;
}
}

Code for Second_Activity.java
 package com.intentdemo;  
import android.app.Activity;
import android.os.Bundle;
public class Second_Activity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
}
}