Android Explicit Intent with Example

Here is source code of the Program demonstrate a Explicit Intent in Android using Java. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

The most common use of Intents is to bind your application components and communicate between them. Intents are used to start Activities, allowing you to create a workflow of different screens.

To create and display an Activity, call startActivity, passing in an Intent, as follows:

Intent myintent = new Intent();
startActivity(myIntent);

The startActivity method finds and starts the single Activity that best matches your Intent.

To select a specific Activity class to start, create a new Intent, specifying the current Activity’s Context and the class of the Activity to launch. Pass this Intent into startActivity() method, as shown

Intent intent = new Intent(this, OtherActivitytostart.class);
startActivity(intent);

You can construct the Intent to explicitly specify the Activity class to open, or to include an action that the target Activity must be able to perform. In the latter case, the run time will choose an Activity dynamically using a process known as intent resolution. When you use startActivity, your application won’t receive any notification when the newly launched Activity finishes. To track feedback from a sub-Activity, use startActivityForResult() method.

advertisement
advertisement

The startActivityForResult method works much like startActivity, but with one important difference. In addition to passing in the explicit or implicit Intent used to determine which Activity to launch, you also pass in a request code. This value will later be used to uniquely identify the sub- Activity that has returned a result.

The below given code shows how to launch Activities Explicitly.

Main Activity

Note: Join free Sanfoundry classes at Telegram or Youtube
 
package com.example.explicit_intent;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity implements OnClickListener {
 
        private static final int REQUEST_CODE1 = 1;
        private static final int REQUEST_CODE2 = 2;
        private Intent intent;
        @Override
         protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_main);
 
               Button b1 = (Button) findViewById(R.id.button1);
               Button b2 = (Button) findViewById(R.id.button2);
               b1.setOnClickListener(this);
               b2.setOnClickListener(this);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
                 getMenuInflater().inflate(R.menu.main, menu);
                 return true;
    }
 
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
               switch (v.getId()) {
                  case R.id.button1:
                      intent = new Intent(this, Activity1.class);
                      intent.putExtra("Value1", "This value one for Activity1 ");
                      intent.putExtra("Value2", "This value two Activity1");
                      startActivityForResult(intent, REQUEST_CODE1);
                      break;
                  case R.id.button2:
                      Intent intent = new Intent(this, Activity2.class);
                      intent.putExtra("Value1", "This value one for Activity2");
                      intent.putExtra("Value2", "This value two Activity2");
                      startActivityForResult(intent, REQUEST_CODE2);
                      break;
         }
      }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
                 if (resultCode == RESULT_OK && requestCode == REQUEST_CODE1) {
                     if (data.hasExtra("returnKey1")) {
                         Toast.makeText(this, data.getExtras().getString("returnKey2"),
                               Toast.LENGTH_SHORT).show();
              }
        }
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE2) {
                        if (data.hasExtra("returnkey2")) {
                             Toast.makeText(this, data.getExtras().getString("returnkey1"),
                                           Toast.LENGTH_LONG).show();
            }
        }
 
    }
}

Activity1

 
package com.example.explicit_intent;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Activity1 extends Activity implements OnClickListener {
 
    private String str1, str2;
    private EditText text1, text2;
        @Override
          protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.layout1);
                Bundle data = getIntent().getExtras();
                if (data == null) {
                    return;
        }
                String value1 = data.getString("Value1");
                String value2 = data.getString("Value2");
                if (value1 != null && value2 != null) {
                      text1 = (EditText) findViewById(R.id.editText1);
                      text2 = (EditText) findViewById(R.id.editText2);
                      Button but = (Button) findViewById(R.id.layout_button1);
                         but.setOnClickListener(this);
                      str1 = text1.getText().toString();
                      str2 = text2.getText().toString();
                      TextView textview1 = (TextView) findViewById(R.id.textView1);
                      TextView textview2 = (TextView) findViewById(R.id.textView2);
                      /*
                       * the text view displays data which are sent to the activity via
                       * intent
                       */
                       textview1.setText(value1);
                       textview2.setText(value2);
        }
    }
 
    @Override
    public void onClick(View view) {
             finish();
    }
 
    @Override
    public void finish() {
                Intent send_data = new Intent();
                send_data.putExtra("returnKey1", "Returned return key1 from Activity1");
                send_data.putExtra("returnKey2", "Returned return key2 from Activity1");
                setResult(RESULT_OK, send_data);
                super.finish();
    }
}

Activity2

 
 
package com.example.explicit_intent;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Activity2 extends Activity implements OnClickListener {
 
    private String str1, str2;
    private EditText text1, text2;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.layout1);
 
               Bundle data = getIntent().getExtras();
                 if (data == null) {
                    return;
                 }
                String value1 = data.getString("Value1");
                String value2 = data.getString("Vlaue2");
                Button b1 = (Button)findViewById(R.id.layout_button1);
                b1.setOnClickListener(this);
 
              if (value1 != null && value2 != null) {
                    text1 = (EditText) findViewById(R.id.editText1);
                    text2 = (EditText) findViewById(R.id.editText2);
                    Button but = (Button) findViewById(R.id.layout_button1);
                    but.setOnClickListener(this);
 
                    str1 = text1.getText().toString();
                    str2 = text2.getText().toString();
 
                     TextView textview1 = (TextView) findViewById(R.id.textView1);
                     TextView textview2 = (TextView) findViewById(R.id.textView2);
                     /*
                      * the text view displays data which are sent to the activity via
                      * intent
                      */
                     textview1.setText(value1);
                     textview2.setText(value2);
 
        }
    }
 
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
                finish();
    }
 
    @Override
    public void finish() {
               Intent send_data = new Intent();
               send_data.putExtra("returnKey1", "Returned return key1 from Activity2");
               send_data.putExtra("returnKey2", "Returned return key2 from Activity2");
               setResult(RESULT_OK, send_data);
               super.finish();
    }
 
}

Activity_Main.xml

advertisement
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@drawable/background" >
 
    <TextView
       android:id="@+id/main_textview_1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Main Activity to launch other activity via Intent Explicitily"
       android:textSize="30dp" >
    </TextView>
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/main_textview_1"
        android:layout_alignRight="@+id/main_textview_1"
        android:layout_centerVertical="true"
        android:text="Launch Activity1" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/main_textview_1"
        android:layout_marginBottom="72dp"
        android:text="Launch Activity2" />
 
</RelativeLayout>

layout1

 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="20dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="TextView"
        android:textSize="20dp" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="20dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="86dp"
        android:text="TextView"
        android:textSize="20dp" />
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="34dp"
        android:ems="10" >
 
        <requestFocus />
    </EditText>
 
    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="41dp"
        android:ems="10" />
 
    <Button
        android:id="@+id/layout_button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="21dp"
        android:text="Click To Finish" />
 
</RelativeLayout>

AndroidManifest

advertisement
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.explicit_intent"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.explicit_intent.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
 
        <activity
            android:name="com.example.explicit_intent.Activity1"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.Activity1" />
 
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
 
 
        <activity
            android:name="com.example.explicit_intent.Activity2"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.Activity2" />
 
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
 
    </application>
 
</manifest>

Capture

Capture1

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.