What is Intent in Android?

What is Intent in Android?

Intents are   asynchronous messages that perform at run time form one component to other component  in same application  or other  application.  Intent use with StartActivity to launch a new Ativity in android application. Intent can communicate mainly three component in android application -
1. Activity
2.Service
3.BroadcastReceiver 

To Start An Activity :
An Activity represent the single screen of application.when we create a new instance of an  Activity by passing the Intent  in startActivity().
If you want to receive the data from Activity after finish the Activity , we use startActivityForResult().

To Start a Service
A service is a component that performs operation in the background without a user interface.we can start a service to perform a one time operation (such as download a file) by passing the Intent in startService().

we can understand Intents other way . suppose we have two activity in an application and we  want to go next activity. for this we use startActivity(Intent intent) method to will land us to next activity. we can send data from one activity to next activity by using intents. we will understand also through programming.

BroadCasstReceiver
BroadCastReciever is a doormat component in android.An Intent can bring it into action.The BroadCastReceiver is to pass a notification to the user ,in case a specific event occur(like when battery goes down the android system show notification such as  your battery low).


NOTE -
Intent implements Parcelable and Cloneable Interface.



Constructing an Intent
Intent Object
intent object  carry the message  which is used by the component that receives the intent plus information used by the Android system.

The basic information contained in an Intent is the following:

Component Name

The name of the component to start. This is Optional

Note: before starting a Service, always specify the component name. Otherwise, there would be some confusion that what service will respond to the intent, and the user cannot see which service has started.

Action

A string which  specifies the type of generic actions to perform like as view or pick(forcing a chooser).

In the case of a broadcast intent, this is the action that took place and is being reported.The action determines how the rest of the intent is structured—specially what is contained in the data and extras.
 There are many Action is defined for specific task you can view the Action List.
we can specify  own set of actions for intents within our  app (or for use by other apps to invoke components in our app), but we should usually use action constants defined by the Intent class or other framework classes. Here are some common actions for starting an activity:

ACTION_VIEW
Use this action in an intent with startActivity() When some information that an activity can show to the user, such as a photo to view in a gallery app, or an address to view in a map app.

ACTION_SEND
Also known as the "share" intent, we should use this in an intent with startActivity() when we have some data that the user can share through another app, such as an email app or social sharing app.
we can specify the action for an intent with setAction() or with an Intent constructor.

If we define our own actions, make sure to include your app's package name as a prefix. For example:

static final String ACTION_TIMETRAVEL = "com.your_package.action.TRAVEL";

DATA

The URI (a Uri object) that references the data to be acted on and/or the MIME type of that data. The type of data supplied is generally determined by the intent's action. For example, if the action is ACTION_EDIT, the data should contain the URI of the document to edit.

Caution: If we want to set both the URI and MIME type, do not call setData() and setType() because they each nullify the value of the other. Always use setDataAndType() to set both URI and MIME type

Category

The category is an optional part of Intent object and it's a string containing additional information about the kind of component that should handle the intent. The addCategory() method places a category in an Intent object,removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently in the object. Here is a list of Android Intent Standard Categories.

Extras

Key-value pairs that carry additional information required to accomplish the requested action. Just to use particular kinds of data URIs, some actions also use particular extras.
we can add extra data with various putExtra() methods, each accepting two parameters: the key name and the value. we can also create a Bundle object with all the extra data, then insert the Bundle in the Intent with putExtras().
For example:- when creating an intent to send an email with ACTION_SEND, we can specify the "to" recipient with the EXTRA_EMAIL key, and specify the "subject" with the EXTRA_SUBJECT key.

Flags
Flags defined in the Intent class that function as metadata for the intent. Flags  instructs the Android system how to launch an activity (for example, which task the activity should belong to)  and how to treat it after it's launched (for example, whether it belongs in the list of recent activities).

Pending Intents

A PendingIntent object is a wrapper around an Intent object. The basic purpose of a PendingIntent is to grant permission to a foreign applications to use the contained Intent as if it were executed from our app's own process.
Major use cases for a pending intent include:
  • Declare an intent to be executed when the user performs an action with your Notification (the Android system's NotificationManager executes the Intent).
  • Declare an intent to be executed when the user performs an action with your App Widget (the Home screen app executes the Intent).
  • Declare an intent to be executed at a specified time in the future (the Android system's AlarmManager executes the Intent).
Because each Intent object is designed to be handled by a unique type of app component (either an Activity, a Service, or a BroadcastReceiver), so too must a PendingIntent be created with the same consideration. When using a pending intent, our app will not execute the intent with a call such as startActivity(). we must instead declare the intended component type when we create the PendingIntent by calling the respective creator method:
  • PendingIntent.getActivity() for an Intent that starts an Activity.
  • PendingIntent.getService() for an Intent that starts a Service.
  • PendingIntent.getBroadcast() for a Intent that starts an BroadcastReceiver.
Unless our app is receiving pending intents from other apps, the above methods to create a PendingIntent are the onlyPendingIntent methods we'll probably ever need.

Intent Filters

we have seen how an Intent has been used to call  another activity. Android OS uses filters to pinpoint the set of Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent. we will use <intent-filter>element in the manifest file to list down actions, categories and data types associated with any activity, service, or broadcast receiver.
Following is an example of a part of AndroidManifest.xml file to specify an activity com.your_package.intentdemo.CustomActivity which can be invoked by either of the two mentioned actions, one category, and one data:
<activity android:name=".CustomActivity"
  android:label="@string/app_name">
  <intent-filter>
     <action android:name="android.intent.action.VIEW" />
     <action android:name="com.wer_packageintentdemo.LAUNCH" />
     <category android:name="android.intent.category.DEFAULT" />
     <data android:scheme="http" />
  </intent-filter>
</activity>
Once this activity is defined along with above mentioned filters, other activities will be able to invoke this activity using either the android.intent.action.VIEW, or using the com.wer_package.intentdemo.LAUNCH action provided in their category is android.intent.category.DEFAULT.
The <data> element specifies the data type expected by the activity to be called and for above example our custom activity expects the data to start with the "http://"
There may be a situation that an intent can pass through the filters of more than one activity or service, the user may be asked which component to activate. An exception is raised if no target can be found.
There are following test Android checks before invoking an activity:
  • A filter <intent-filter> may list more than one action as shown above but this list cannot be empty; a filter must contain at least one <action> element, otherwise it will block all intents. If more than one actions are mentioned then Android tries to match one of the mentioned actions before invoking the activity.
  • A filter <intent-filter> may list zero, one or more than one categories. if there is no category mentioned then Android always pass this test but if more than one categories are mentioned then for an intent to pass the category test, every category in the Intent object must match a category in the filter.
  • Each <data> element can specify a URI and a data type (MIME media type). There are separate attributes likescheme, host, port, and path for each part of the URI. An Intent object that contains both a URI and a data type passes the data type part of the test only if its type matches a type listed in the filter.





Types of Intent
There are two types of Intent.
1. Implicit Intents
2. Explicit Intents

Implicit Intent
it do not name have a target name and the field for component is blank. We can say , we use ACTIVITY  ACTION  in the implicit intents.Activity Action is predefined Intent.
For example  Android system view a webpage.

Intent intent = new Intent(Intent.Action_View,Uri.Parse("http://androidheight.blogspot.in/2015/02/what-is-activity-in-android.html");
startActivity(intent);

Explicit Intent

Explicit intent explicitly defined the defined the target component that is called by Android System.we use the java class as a target component.In simple way ,it is defined by user and carry the message to other component.

For eample-
The syntax for Explicit intent
Intent intent =new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("name","prabhakar");
startActivity(intent);










Send The Integer Data from one Activity to another Activity


get the Integer Value ,then using Intent object you can send data to specific Activity


  int Password =Integer.parseInt(etPassword.getText().toString());

  Intent  intent  = new Intent(MainActivity.this,SecondActivity.class);
                intent.putExtra("pass",Password);
                startActivity(intent);


In other Activity ,Get the Intent Value

        Bundle bundle = getIntent().getExtras();
       int value =bundle.getInt("pass");

use same concept for float ,long and double value
for Float - bundle.getFloat("String key");
Long - bundle.getLong("String Key");
Double - bundle.getDouble("String Key");


Now I share example that will help you  to understand the Intent 

activity_main.xml


<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:hint="Enter UserName"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberPassword"
        android:ems="10"
        android:id="@+id/editText2"
        android:hint="Enter Password"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/button" />
</LinearLayout>


activity_second.xml
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="intent.androidheight.intentdemo.SecondActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="UserName"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Password"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="40dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Read about Activity"
        android:id="@+id/tvActivity"
        android:layout_below="@+id/textView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="40dp"
        android:layout_marginStart="40dp"
        android:layout_marginTop="54dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/tvusername"
        android:layout_alignBottom="@+id/textView"
        android:layout_toRightOf="@+id/tvActivity"
        android:layout_toEndOf="@+id/tvActivity" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/tvpassword"
        android:layout_above="@+id/tvActivity"
        android:layout_toRightOf="@+id/tvActivity"
        android:layout_toEndOf="@+id/tvActivity" />
</RelativeLayout>

MainActivity.java
package intent.androidheight.intentdemo;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends ActionBarActivity {
private EditText etUserName,etPassword;
    private Button btnSubmit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etUserName =(EditText)findViewById(R.id.editText);
        etPassword = (EditText)findViewById(R.id.editText2);
        btnSubmit = (Button)findViewById(R.id.button);

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = etUserName.getText().toString();
                int Password =Integer.parseInt(etPassword.getText().toString());

                //here using Explicit Intent to send the String type username
                // and integer type password to second Activity
                Intent  intent  = new Intent(MainActivity.this,SecondActivity.class);
                intent.putExtra("user",userName);
                intent.putExtra("pass",Password);
                startActivity(intent);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

SecondActivity.java

package intent.androidheight.intentdemo;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;


public class SecondActivity extends ActionBarActivity {
TextView tvUsername,tvPassword,tvActivity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        tvUsername =(TextView)findViewById(R.id.tvusername);
        tvPassword =(TextView)findViewById(R.id.tvpassword);
        tvActivity =(TextView)findViewById(R.id.tvActivity);
        //here getting the username and password
        Bundle bundle = getIntent().getExtras();
        tvUsername.setText(bundle.getString("user"));
        tvPassword.setText(""+(bundle.getInt("pass")));

        tvActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //here using implicit Intent
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://androidheight.blogspot.in/2015/02/what-is-activity-in-android.html")));
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="intent.androidheight.intentdemo" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".SecondActivity"
            android:label="@string/title_activity_second" >
        </activity>
    </application>

</manifest>


Output






Download sample Project From:  GitHub
SHARE

About prabhakar jha

    Blogger Comment
    Facebook Comment

1 comments:

  1. With the PC being utilized for basically more than figuring, you can discover news sources setting up the intensity of this medium. You have certain absolutely operational blogs which give centered content. medios independientes

    ReplyDelete