Understanding Intents

Android folds multiple ideas into the concept of an intent. You can use intents to invoke other applications from your application. You can use intents to invoke internal or external components from your application. You can use intents to raise events so that others can respond in a manner similar to a publish-and-subscribe model. You can use intents to represent actions.

At the simplest level, an intent is an action that you can tell Android to invoke. The action Android invokes depends on what is registered for that action. Imagine you've written the following activity:

public class BasicViewActivity extends Activity {

^Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.some-view);

Android allows you to register this activity in its manifest file, making it available for other applications to invoke. The registration looks like this:

<activity android:name="BasicViewActivity" android:label="Basic View Tests"> <intent-filter>

<action android:name="com.androidbook.intent.action.ShowBasicView"/>

<category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>

The registration here not only involves an activity, but also an action that you can use to invoke that activity. The activity designer usually chooses a name for the action and specifies that action as part of an intent-filter for this activity. As we go through the rest of the chapter, you will have a chance to learn more about these intent-filters.

Now that you have specified the activity and its registration against an action, you can use an intent to invoke this BasicViewActivity:

public static invokeMyApplication(Activity parentActivity) {

String actionName= " com.androidbook.intent.action.ShowBasicView ";

Intent intent = new Intent(actionName); parentActivity.startActivity(intent);

Note The general convention for an action name is <your-package-name>.intent.action.YOUR ACTION NAME.

0 0

Post a comment