Thursday, July 23, 2015

Intents and intent filter

1. Intents and intent filter
1.1. What are intents?
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. Your code can send them to the Android system defining the components you are targeting. For example, via the startActivity() method you can define that the intent should be used to start an activity.
An intent can contain data via a Bundle. This data can be used by the receiving component.
1.2. Starting activities
To start an activity, use the method startActivity(intent). This method is defined on the Context object which Activity extends.
Start activity via an intent
The following code demonstrates how you can start another activity via an intent.
# Start the activity connect to the
# specified class

Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);

The following shows how to create an explicit intent and send it to the Android system. If the class specified in the intent represents an activity, the Android system starts it.
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
Explicit intents are typically used within on application as the classes in an application are controlled by the application developer.
2. Data transfer between activities
2.1. Data transfer to the target component
An intent contains certain header data, e.g., the desired action, the type, etc. Optionally an intent can also contain additional data based on an instance of the Bundle class which can be retrieved from the intent via the getExtras() method.
You can also add data directly to the Bundle via the overloaded putExtra() methods of the Intent objects. Extras are key/value pairs. The key is always of type String. As value you can use the primitive data types (int, float, ...) plus objects of type String, Bundle, Parceable and Serializable.
The receiving component can access this information via the getAction() and getData() methods on the Intent object. This Intent object can be retrieved via the getIntent() method.
The component which receives the intent can use the getIntent().getExtras() method call to get the extra data. That is demonstrated in the following code snippet.
Bundle extras = getIntent().getExtras();
if (extras == null) {
 return;
}
// get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
 // do something with the data
}

No comments:

Post a Comment