Pages

Ads 468x60px

Wednesday, 3 July 2013

Linking Activities Using Intents

An Android application can contain zero or more activities. When your application has more than one activity, you may need to navigate from one activity to another. In Android, you navigate between activities  through what is known as an intent.

The best way to understand this very important but somewhat abstract concept in Android is to experience it first hand and see what it helps you to achieve.The following Try It Out shows how to add another activity to an existing project and then navigate between the two activities.

Linking Activities with intents

1 Using the Activities project created earlier, add the following statements in bold to the
AndroidManifest.xml file:

<?xml version=”1.0” encoding=”utf-8”?>
      <manifest xmlns:android=”http://schemas.android.com/apk/res/android”
             package=”net.learn2develop.Activities”
              android:versionCode=”1”
              android:versionName=”1.0”>
       <application android:icon=”@drawable/icon” android:label=”@string/app_name”>
       <activity android:name=”.MainActivity”  android:label=”@string/app_name”
          android:theme=”@android:style/Theme.Dialog” >
       <intent-filter>
          <action android:name=”android.intent.action.MAIN” />
          <category android:name=”android.intent.category.LAUNCHER” />
      </intent-filter>
  </activity>
   <activity android:name=”.Activity2” android:label=”Activity 2”>
<intent-filter>
   <action android:name=”net.learn2develop.ACTIVITY2” />
   <category android:name=”android.intent.category.DEFAULT” />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion=”9” />

2. Right click on the package name under the src folder and select New ➪ Class (see Figure  ).

3. Name the new class fi le Activity2 (see Figure) and click Finish.

4. Make a copy of the main.xml file by right-clicking on it and selecting Copy. Then, right-click on the res/layout folder and select Paste. Name the file activity2.xml. The res/layout folder will now contain the activity2.xml file (see Figure)




5. Modify the activity2.xml file as follows:

  <?xml version=”1.0” encoding=”utf-8”?>
       <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
             android:orientation=”vertical”
             android:layout_width=”fill_parent”
             android:layout_height=”fill_parent” >
<TextView
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”This is Activity 2!”
/> </LinearLayout>

6. In the Activity2.java file, add the following statements in bold:
    package net.learn2develop.Activities;
        import android.app.Activity;
        import android.os.Bundle;
        public class Activity2 extends Activity {
    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);
        }
    }

7. Modify the MainActivity.java file as shown in bold:

    package net.learn2develop.Activities;
            import android.app.Activity;
            import android.os.Bundle;
            import android.util.Log;
            import android.view.Window;
            import android.view.KeyEvent;
            import android.content.Intent;
        public class MainActivity extends Activity
        {
                String tag = “Events”;
            /** Called when the activity is first created. */
        @Override
            public void onCreate(Bundle savedInstanceState)
            {
                super.onCreate(savedInstanceState);
                //---hides the title bar---
                //requestWindowFeature(Window.FEATURE_NO_TITLE);
                setContentView(R.layout.main);
                Log.d(tag, “In the onCreate() event”);
            }
        public boolean onKeyDown(int keyCode, KeyEvent event)
        {
            if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
            {
            startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
    }
          return false;
  }
             public void onStart() { //... }
             public void onRestart() { //... }
             public void onResume() { //... }
             public void onPause() { //... }
             public void onStop() { //... }
             public void onDestroy() { //... }
   }

8. Press F11 to debug the application on the Android Emulator. When the first activity is loaded, click the center of the directional pad (see Figure), on a real device this can be achieved by pressing down the trackball). The second activity will now be loaded.


How It Works

As you have learned, an activity is made up of a UI component (for example, main.xml) and a class component (for example, MainActivity.java). Hence, if you want to add another activity to a project, you need to create these two components.

In the AndroidManifest.xml file, specifically you have added the following:
     <activity android:name=”.Activity2”
             android:label=”Activity 2”>
<intent-filter>
        <action android:name=”net.learn2develop.ACTIVITY2” />
        <category android:name=”android.intent.category.DEFAULT” />
        </intent-filter>
</activity>

Here, you have added a new activity to the application. Note the following:

➤➤ The name of the new activity added is “Activity2”.

➤➤ The label for the activity is named “Activity 2”.

➤➤ The intent filter name for the activity is “net.learn2develop.ACTIVITY2”. Other activities that wish to call this activity will invoke it via this name. Ideally, you should use the reverse domain name of your company as the intent filter name in order to reduce the chances of another application having the same intent filter. The next section discusses what happens when two or more activities have the same intent filter.

➤➤ The category for the intent filter is “android.intent.category.DEFAULT”. You need to add this to the intent filter so that this activity can be started by another activity using the startActivity() method (more on this shortly). In the MainActivity.java file, you implemented the onKeyDown event handler. This event is fired whenever the user presses one of the keys on the device. When the user presses the center key on the directional pad (as represented by the KeyEvent.KEYCODE_DPAD_CENTER constant), you use the startActivity() method to display Activity2 by creating an instance of the Intent class and passing it the intent filter name of Activity2 (which is net.learn2develop.ACTIVITY2):

   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
           if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
           {
                startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
           }
        return false;
  }

Activities in Android can be invoked by any application running on the device. For example, you can create a new Android project and then display Activity2 by using its net.learn2develop.ACTIVITY2 intent filter. This is one of the fundamental concepts in Android that enables an application to invoke another easily.
If the activity that you want to invoke is defined within the same project, you can rewrite the preceding statement like this:

startActivity(new Intent(this, Activity2.class));
However, this approach is applicable only when the activity you want to display is within the same project as the current activity.

0 التعليقات:

Post a Comment

.

Education blog