Working with Android Intents

faribasiddiq's Avatar author of Working with Android Intents
Intent is used to performing tasks in an android application this tutorial covers how to get started working with android intents along with type of intents..
Intent is a message passing mechanism. Generally intents are used to support interaction between different application components. The main tasks performed by intent are:
  • Start new activity or service
  • Pass data between activities or services
  • Delegate other application to perform any task

Types of Intents

  • Explicit intent
  • Implicit intent

Explicit intent



In explicit intent, you have to specify the component name that needs to be loaded. Generally, if you want to open a new activity from the current activity of the same application, you should use explicit intent.

Add new activity:

You can add a new activity from options of your editor. Choose File->New->Other



Choose Android Activity from the list.



Choose Blank Activity.



Choose project name, write the new activity name and layout name of the new activity. Then click finish. A new activity will be added to your project.



To start a new intent explicitly, you just need to mention the application context and the activity name that needs to be started. For example, look at the following code:

Code:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
Parameters:
  • getApplicationContext():Return the context of the single, global Application object of the current process.
  • SecondActivity.class: The activity class name that needs to be started.
The alternative way is to mention the current activity name in the first parameter.

Code:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
So, the intent object has been created. Now you need to start the intent. The code below performs the task:

Code:
startActivity(intent);
Pass and receive data through explicit intent:

The previous example just starts a new activity from the current activity. In some cases, you may need to pass data from one activity to another. Explicit intent exposes some way to perform the task.

Method 1: key value coding

1. Put Data

You can put data in an intent using putExtra method. It’s a KVC(key value coding) method.

Code:
public Intent putExtra (String name, String value)
Add extended data to the intent.

Parameters
  • name: The name of the extra data.
  • value: The String data value.
Returns
  • Returns the same Intent object, for chaining multiple calls into a single statement.

In our application, we will send a string value from one activity to another activity. We will use the following code to perform the task:

Code:
final EditText et = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent =  new Intent(MainActivity.this, SecondActivity.class);
		intent.putExtra("text", et.getText().toString());
		startActivity(intent);
	}
An EditText control is used to get input text from user. A Button control is used to handle the click event. In clickListener event, we have done following tasks:
  • We create a intent object
  • Take the data from edit text control
  • Put data in intent
  • Start new activity using the intent object.
You can send multiple data using same method.

2. Retrieve Data

We have experienced how to send data from one activity to another activity. Now we need to retrieve the data in the second activity. We have used getIntent().getExtras().getText() method to perform the task. Here is a description of the used method.

Code:
public Intent getIntent ()
Return the intent that started this activity.

public Bundle getExtras () - Retrieves a map of extended data from the intent.

Returns
  • the map of all extras previously added with putExtra(), or null if none have been added.

The code snippet is:
Code:
 
        TextView tv = (TextView) findViewById(R.id.textView1);
        String Name = getIntent().getExtras().getString("text");
        String Greeting = "Hi"+" "+Name+","+" "+"how are you?";
        tv.setText(Greeting);
The performed tasks are:
  • Take a TextView control.
  • Retrieve the string value that has been passed to this activity
  • Save the value in a String.
  • Append some more string with it
  • Display a greeting text in the textview, associated with the passed data.
Method 2: using Bundle

1. Put Data:

Another way to put data is using Bundle. According to its name, it offers a way to send bundle of data from one activity to another. Here is a working example:
Code:
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putInt(("text", et.getText().toString);
intent.putExtras(bundle);
startActivity(intent);
2. Retrieve Data:

Now we need to retrieve data in second activity.
Code:
Bundle bundle = getIntent().getExtras();

String Name = bundle.getString("text");
The performed tasks are:
  • Get the needed bundle
  • Get the data from the bundle using the key

Here are the source code of the activities, layout files and manifest files.

MainActivity
Code:
package com.example.intentexample;
 
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.EditText;
 
public class MainActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        final EditText et = (EditText) findViewById(R.id.editText1);
        Button btn = (Button) findViewById(R.id.button1);
       
        btn.setOnClickListener(new OnClickListener() {
                                   
                                    public void onClick(View v) {
                                                // TODO Auto-generated method stub
                                                Intent intent =  new Intent(MainActivity.this, SecondActivity.class);
                                                intent.putExtra("text", et.getText().toString());
                                                startActivity(intent);
                                               
                                    }
                        });
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
Second Activity:
Code:
package com.example.intentexample;
 
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
 
public class SecondActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
       
        TextView tv = (TextView) findViewById(R.id.textView1);
        String Name = getIntent().getExtras().getString("text");
        String Greeting = "Hi"+" "+Name+","+" "+"how are you?";
        Log.d("Name", Greeting);
        tv.setText(Greeting);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_second, menu);
        return true;
    }
}
Activity_main.xml
Code:
<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" >
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="48dp"
        android:ems="10"
        android:inputType="textNoSuggestions" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="45dp"
        android:layout_marginTop="89dp"
        android:text="Button" />
</RelativeLayout>
Activity_second.xml:
Code:
<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" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="49dp"
        android:layout_marginTop="49dp"
        android:text="TextView" />
 
</RelativeLayout>
AndroidManifest.xml:
Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.intentexample"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="@string/title_activity_second" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
Here is the screen shot of the application.

First screen:
  • Enter some text in the edit text control.
  • Press the button below to the text.


Next Screen:
  • The text that has been inserted in the first screen, is passed to the next screen
  • Some greeting text is shown along with the passed text.


Implicit Intent



In implicit intent, you don’t need to specify the component name to perform any job. You just need to mention the action, either the system will decide itself which component to use or the user will get option to choose a component to perform the task.

Example: Suppose you want to view a web page in your application. You don’t need to specify the component name which will do the job for you. Just provide the URL to load, system itself will decide which component will load the webpage for you, or the user will get options to choose any browser if multiple browser is installed in the system.

In our application, we are using implicit intent to open a web page. Here is the code snippet:
Code:
        Intent intent=new Intent(Intent.ACTION_VIEW); 
        intent.setData(Uri.parse("http://www.google.com")); 
        startActivity(intent);
The performed tasks are:
  • Create an intent object specifying the action.
  • ACTION_VIEW requests the system to display data to the user.
  • Based on the context passed, Android automatically decides which application to use.
  • Start the activity.
ACTION_VIEW is the common action that is used. According to the URI schema of the supplied data, different applications handle different types of view requests.
  • http address: Open in the browser,
  • tel address : Open in the dialer.
  • geo address: Open in the Google Maps application
  • contact : Open in the Contact Manager
Implicit intents are mainly used for some common activities. Here is a list of them:
  • Launch website
  • Open google play store
  • Show google map
  • Share content
  • Capture image
  • Compose sms
  • Send email
  • Dial phone number
Let’s see what you need to do to dial a phone number as implicit intent from your activity.

Step 1:

Add permission in AndroidManifest.xml file: Use the following code snippet in manifest file to use the phone call facilities from your application.

Code:
<uses-permission android:name="android.permission.CALL_PHONE" />
Step 2:

Create a new Intent object with the action ACTION_CALL.

Code:
Intent intent = new Intent(Intent.ACTION_CALL);
Use setData function set the scheme and phone number. Use “tel” scheme for telephone.

Code:
intent.setData(Uri.parse("tel:01717777777"));
Start the activity.

Code:
startActivity(intent);
Here is the source code of the activity, layout and manifest file.

AndroidManifest.xml:
Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.impliciteintent"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
 
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
MainActivity
Code:
package com.example.impliciteintent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
 
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent=new Intent(Intent.ACTION_VIEW); 
        intent.setData(Uri.parse("http://www.google.com")); 
        startActivity(intent); 
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }  
}
shabbir like this