Tuesday, April 10, 2012

Android explicit intent

Having introduced you to the basic anatomy of an android application in the Part 1 of the series, I would like to show you an example where communication between 2 activities happens through an intent. 

However, just one more detail to be introduced as promised and that is -
There are 2 types of intents that Android understands.
1. Explicit Intent
2. Implicit Intent

In an Explicit intent, you actually specify the activity that is required to respond to the intent. In other words, you explicitly designate the target component. This is typically used for application internal messages.

In an Implicit intent (the main power of the android design), you just declare an intent and leave it to the platform to find an activity that can respond to the intent. Here, you do not declare the target component and hence is typically used for activating components of other applications seamlessly
Note: Here for simplicity sake I tell an activity responds to an intent, it could as well be other types of components.
Now I will jump into the example which you can download from here:

This example has 2 activities:
1. InvokingActivity
2. InvokedActivity
The InvokingActivity has a button "Invoke Next Activity" which when clicked explicitly calls the "InvokedActivity" class.
The relevant part of the code is here:

        Button invokingButton = (Button)findViewById(R.id.invokebutton);
        invokingButton.setOnClickListener(new OnClickListener() {
        
         public void onClick(View v) {
         Intent explicitIntent = new Intent(InvokingActivity.this,InvokedActivity.class);
         startActivity(explicitIntent);
         }
        });

As explained in part 1 of the series, this is very much like an API call with compile time binding.
NOTE: The layout for InvokingActivity is defined in main.xml and for InvokedActivity in InvokedActivity.xml. The downloadable example can be opened in Eclipse Ganymede as an android project and can be executed.
In the next part of the series, we will see how to work with implicit intents which also needs us to understandintent-filters.

No comments:

Post a Comment