Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Sending an intent to other apps

The intent created in this lesson is what's considered an explicit intent, because the Intent specifies the exact app component to which the intent should be given. However, intents can also be implicit, in which case the Intent does not specify the desired component, but allows any app installed on the device to respond to the intent as long as it satisfies the meta-data specifications for the action that's specified in various Intent parameters. For more information, see the class about Interacting with Other Apps.

Note: The reference to DisplayMessageActivity will raise an error if you’re using an IDE such as Eclipse because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon.

An intent not only allows you to start another activity, but it can carry a bundle of data to the activity as well. Inside the sendMessage() method, use findViewById() to get the EditText element and add its text value to the intent:

Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);

Note: You now need import statements for android.content.Intent and android.widget.EditText. You'll define the EXTRA_MESSAGE constant in a moment.

An Intent can carry a collection of various data types as key-value pairs called extras. The putExtra() method takes the key name in the first parameter and the value in the second parameter.

In order for the next activity to query the extra data, you should define the key for your intent's extra using a public constant. So add the EXTRA_MESSAGE definition to the top of the MainActivity class:

public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
...
}

It's generally a good practice to define keys for intent extras using your app's package name as a prefix. This ensures they are unique, in case your app interacts with other apps.


Date: 2014-12-29; view: 800


<== previous page | next page ==>
Starting Another Activity | Create the Second Activity
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.006 sec.)