Archive for December, 2011
Explicit Intent
Posted by Deepthi Girija Thampi in Android on December 24, 2011
Now, lets see how the components in android communicate.
Communication between the three core components in android-activity, service and broadcast receiver is made possible using intents. Intents can be said as messages passed between these components. An Intent object is a bundle of information containing information such as the action to be performed, data on which the action is to be performed etc.
Intents are of two types: Explicit intents and Implicit intents
Here , in this post, I’m discussing about Explicit Intent.
Explicit intents: They specify the target component by its name.That is, they explicitly specify the target component which needs to respond to it.
Here is how it is done:
Intent intent=new Intent(source.this,destination.class);
Or
Intent intent=new Intent(); Intent.setClass(source.this,destination.class);
Lets see what an explicit intent is and how it works through a simple example.
Code for the Source activity :
public class Source extends Activity { /** Called when the activity is first created. */ Button dest; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); dest=(Button)findViewById(R.id.click); dest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent=new Intent(Source.this,Destination.class); startActivity(intent); } }); } }
The XML code for main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click to go to destination" android:textSize="20dip" /> </LinearLayout>
This is how the UI looks:
Code for the Destination activity:
public class Destination extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.maindest); } }
XML code for maindest.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#FFF"> <TextView android:id="@+id/textView1" android:layout_width="278dp" android:layout_height="wrap_content" android:text="Welcome to Destination" android:textSize="25dip" android:textColor="#0000ff" /> </LinearLayout>
The Output When the Button on the Source UI is clicked :
Hope this helped you in understanding an Intent and how it works.