Passing Information with Intents

Intents can be used to pass data between activities. You can use an intent in this way by including additional data, called extras, within the intent.

To package extra pieces of data along with an intent, you use the putExtra() method with the appropriate type of object you want to include. The Android programming convention for intent extras is to name each one with the package prefix (for example, com.androidbook.chippy.NameOfExtra).

For example, the following intent includes an extra piece of information, the current game level, which is an integer:

Intent intent = new Intent(getApplicationContext(), HelpActivity.class); intent.putExtra("com.androidbook.chippy.LEVEL", 23); startActivity(intent);

When the HelpActivity class launches, the getIntent() method can be used to retrieve the intent. Then the extra information can be extracted using the appropriate methods. Here's an example:

Intent callinglntent = getIntent();

int helpLevel = callingIntent.getIntExtra("com.androidbook.chippy.LEVEL", 1);

This little piece of information could be used to give special Help hints, based on the level.

For the parent activity that launched a subactivity using the startActivityForResult() method, the result will be passed in as a parameter to the onActivityResult() method with an Intent parameter. The intent data can then be extracted and used by the parent activity.

0 0

Post a comment