Pages

Wednesday, August 29, 2012

Intent & Intent Filters

What is Intent?

Intent is kind of asynchronous message to Android components. Android component reacts on that message. Intent can be sent by an Activity to Android system which can start another Activity.

This is totally asynchronous, so it is stateless. Starting another activity using Intent is loosely coupled.

Intent is a class in android.content package. To send an intent, you have to create an instance of Intent class.

Android system receive message from Intent and based on that message system decide what to do next.

Other then message Intent can contain some date to send. If you have scene precious article of Login, I have sent user name to next activity using Intent.

Intent can call user define activity or system activities like Browser, Contact List, Call Activity, etc. To send intent to system activities there are constants created in android. User can use those predefined constants to intent those activities.

Intent can be used with startActivity() to launch an Activity, it can be broadcastIntent() to send it to interested BroadcastReceiver component, and startService(Intent)  or bindService(Intent, ServiceConnection, int) to communicate with a background service.

Intent Object
 
An intent object is bundle of information. It contain information of component that receives the intent such as the action to be taken and the data to act on plus information of the android system such as the category of component that should handle the intent and instructions on how to launch a target activity.

Main information in intent are:
  • Action: The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.
  • Data: The data to operate on, such as a person record in the contacts database, expressed as a Uri.
Other then above two main information in Intent, there are many optional attributes you can include with an Intent.
  • category -- Gives additional information about the action to execute. For example, CATEGORY_LAUNCHER means it should appear in the Launcher as a top-level application, while CATEGORY_ALTERNATIVE means it should be included in a list of alternative actions the user can perform on a piece of data.

  • type -- Specifies an explicit type (a MIME type) of the intent data. Normally the type is inferred from the data itself. By setting this attribute, you disable that evaluation and force an explicit type.

  • component -- Specifies an explicit name of a component class to use for the intent. Normally this is determined by looking at the other information in the intent (the action, data/type, and categories) and matching that with a component that can handle it. If this attribute is set then none of the evaluation is performed, and this component is used exactly as is. By specifying this attribute, all of the other Intent attributes become optional.

  • extras -- This is a Bundle of any additional information. This can be used to provide extended information to the component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc.

Intent Resolution

There are two main forms of intents you can use.
  • Explicit Intents have specified a component (via setComponent(ComponentName) or setClass(Context, Class)),  which provides the exact class to be run. Often these will not include any other information, simply being a way for an application to launch various internal activities it has as the user interacts with the application.
  • Implicit Intents have not specified a component; instead, they must include enough information for the system to determine which of the available components is best to run for that intent.

Android delivers an explicit intent to an instance of the designated target class. Nothing in the Intent object other than the component name matters for determining which component should get the intent. 

A different strategy is needed for implicit intents. In the absence of a designated target, the Android system must find the best component (or components) to handle the intent — a single activity or service to perform the requested action or the set of broadcast receivers to respond to the broadcast announcement. It does so by comparing the contents of the Intent object to intent filters, structures associated with components that can potentially receive intents. Filters advertise the capabilities of a component and delimit the intents it can handle. They open the component to the possibility of receiving implicit intents of the advertised type. If a component does not have any intent filters, it can receive only explicit intents. A component with filters can receive both explicit and implicit intents.

Only three aspects of an Intent object are consulted when the object is tested against an intent filter: 
  • Action
  • Date (both URI and data type)
  • Category

Intent Filter

If an Intent is send to the Android system, it will determine suitable applications for this Intent. If several components have been registered for this type of Intent, Android offers the user the choice to open one of them. 

This determination is based on IntentFilters. An IntentFilter specifies the types of Intent that an activity, service, or broadcast receiver can respond to. An IntentFilter declares the capabilities of a component. It specifies what an Activity or Service can do and what types of broadcasts a Receiver can handle. It allows the corresponding component to receive Intents of the declared type. 

IntentFilter are typically defined via the AndroidManifest.xml file. For BroadcasrReceiver it is also possible to define them in coding. An IntentFilter is defined by its category, action and data filters. It can also contain additional metadata.

To inform the system which implicit intents they can handle, activities, services, and broadcast receivers can have one or more intent filters. Each filter describes a capability of the component, a set of intents that the component is willing to receive. It, in effect, filters in intents of a desired type, while filtering out unwanted intents — but only unwanted implicit intents (those that don't name a target class). An explicit intent is always delivered to its target, no matter what it contains; the filter is not consulted. But an implicit intent is delivered to a component only if it can pass through one of the component's filters.  

An intent filter is an instance of the IntentFilter class. However, since the Android system must know about the capabilities of a component before it can launch that component, intent filters are generally not set up in Java code, but in the application's manifest file (AndroidManifest.xml) as <intent-filter> elements. (The one exception would be filters for broadcast receivers that are registered dynamically by calling Context.registerReceiver(); they are directly created as IntentFilter objects.)

A filter has fields that parallel the action, data, and category fields of an Intent object. An implicit intent is tested against the filter in all three areas. To be delivered to the component that owns the filter, it must pass all three tests. If it fails even one of them, the Android system won't deliver it to the component — at least not on the basis of that filter. However, since a component can have multiple intent filters, an intent that does not pass through one of a component's filters might make it through on another.

Sunday, August 26, 2012

Login application in Android!!

In my previous article I have explained about Button and event for Button. Let's jump in deep in these events.

Here is a program for Login. This application will ask you credential to enter, will provide appropriate message on some wrong attempt and will allow you to go to next screen on successful Lgoin.

In this application we'll need two activities, one is the initial which ask user for credential and second which displays user name on successful login. To add another activity to you Android project follow below steps.

1. Right click on your project and go toNew -> Others...
2. Select Android Activity from Android option.
3. Keep selecting Blank Activity on screen and press next.
4. Give your new Activity's name, here I have given Welcome.

So, after creating new activity two new things will be added in your project.

1. Welcome.java in src folder
2. activity_welcome.xml file in res -> layout folder.

In this application you only need to design activity_login.xml.

1. Design Layout:

I have used some new layout in this application and some new widgets. Take a look at screen and an XML code of activity_login.xml layout of Login application design.


I have taken two EditText and two Buttons. Take a look at below XML code for above design.
Code of activity_login.xml



        

        
        
        
            
      


Here in this design I have taken two <LinearLayout>, the first one with vertical orientation which arrange both EditText plus the second <LinearLayout> in a column. The second <LinearLayout> with horizontal orientation which arrange both Buttons in a Row. 

Second layout and both EditText reside inside first layout and both button reside inside second layout.

Thats it, design finished here, let's move on to resources.

2. Add or Create resources:

 I have created some resources in string.xml file. Below is code for that.



    Login
    Hello world!
    Settings
    Login
    Enter Username
    Enter Password
    Sign In
    Clear
    Welcome





3. Write class file:

In class file we are going to code some validations and events. You have to write below code in you Login.java file.

package com.android.login;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.text.InputType;

public class Login extends Activity {

 EditText username;
 EditText password;
 Button signin;
 Button clear;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        username = (EditText) findViewById(R.id.edit_username);
        password = (EditText) findViewById(R.id.edit_password);
        signin = (Button) findViewById(R.id.btn_signin);
        clear = (Button) findViewById(R.id.btn_clear);
        
        username.setOnTouchListener(new OnTouchListener() {
   
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    int inType = username.getInputType();   //backup input type
    username.setInputType(InputType.TYPE_NULL);  //disable soft input
    username.onTouchEvent(event);     //call native handler
    username.setInputType(inType);     //restore input type
    
    return true;         //consume touch even
   }
  });

        password.setOnTouchListener(new OnTouchListener() {
   
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    int inType = password.getInputType();   //backup input type
    password.setInputType(InputType.TYPE_NULL);  //disable soft input
    password.onTouchEvent(event);     //call native handler
    password.setInputType(inType);     //restore input type
    
    return true;         //consume touch even
   }
  });
        
        clear.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    username.setText("");
    password.setText("");
    username.requestFocus();
   }
  });
        
        signin.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    if(username.getText().toString().equals("") || password.getText().toString().equals(""))
    {
     Toast.makeText(Login.this, "Invalid Username/Password", Toast.LENGTH_LONG).show();
    }
    else if(username.getText().toString().equals("android") && password.getText().toString().equals("rises"))
    {
     Intent i = new Intent(Login.this,Welcome.class);
     i.putExtra("user", username.getText().toString());
     startActivity(i);
    }
    else
    {
     Toast.makeText(Login.this, "Invalid Username/Password", Toast.LENGTH_LONG).show();
    }
   }
  });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }    
}

As you can see in Java file I have taken objects of both EditText and Button in onCreate() method. 

Let's take a look at all methods in details. 

1. username.setOnTouchListener(new OnTouchListener):

If you have seen in any Android phone, when you touch on any text box, a key board on the screen come up. So, in case if your phone have qwerty keyboard in your phone you have to block that virtual key board on screen. I have written code to block that virtual code in this method.

This method will fire when user touch on the username text box and date from text box will copied to an integer variable, then text box will be set to Null by setInputType(int) method.

Same I have coded for password text box.

2. clear.setOnClickListener():

In this method I have cleared both text box and moved focus to username text box.
3. signin.setOnClickListener():

When user click on this button, if credentials are right welcome screen will come up, other wise an error message will flash on screen.

To flash message on screen I have used Toast

Toast.makeText(Login.this, "Invalid Username/Password", Toast.LENGTH_LONG).show();

makeText() of Toast class used to create flash message. First argument is this pointer of the screen class where you want to flash message. Second argument is the message you want to flash and third is time duration. Time duration can only set either LENGTH_LONG or LENGTH_SHORT. 

show() method actually display message on screen.

This all process executes if user enter wrong credential but, if user enter correct credential new activity will execute. So, you have to learn how to call new activity.

In this application another activity created is Welcome. On successful login the else if part will execute. I have create object of Intent class. Intent is a class which you can use to call another activity. Calling activity can be user created or system created like Contacts, Message, etc.

Intent i = new Intent(Login.this, Welcome.class);

Above statement will create i object of Intent class. Object is created by calling  constructor. First argument in constructor is this pointer of activity from where you are starting new activity. Second argument is class of the calling activity.

i.putExtra("user", username.getText());

Above method is used to pass some data to next activity. This will pass username who is signing in to the application. "user" is key to access the username in activity we are calling.

startActivity(i);

This method belong to Activity class. You can use this method to call new activity. As an argument you just need to pass Intent class' object.
This all is enough to start new activity. Let's check out what happening in this new activity. 

Below is a code of Welcome.java file.

package com.android.login;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class Welcome extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        TextView tv = (TextView)findViewById(R.id.textWelcome);
        Bundle b = getIntent().getExtras();
        String user = b.getString("user");
        tv.setText("Welcome, " + user + "!");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_welcome, menu);
        return true;
    }

    
}

In this activity I have just display username in a textview which passed from Login activity. You know how to create object of textview using findViewById.
Here I have use Bundle class, take a look at it.

Bundle b = getIntent().getExtras();

getIntent() is method of activity class. It returns intent that started this activity. In this case Login activity started Welcome activity so, getIntent() here will return intent of Login activity.

getExtras() is method of Intent class. It receives all extended data from intent. Here it will return Bundle object.

String user = b.getString("user");

This will return the value associated with the given key. Here in this application key is "user" and value is username. So, string user will get the username passed from Login activity.

The complete application will look something like this.

Login Activity
  
Welcome Activity


Thats it. You are done!!!

Saturday, August 25, 2012

Working with Button and its event...

We looked at Hello World program which describes TextView widget. Let's have a look at Button.

In this program we'll perform Button's click event and we'll display number of clicks in TextView.

1. Design layout



You can see I have taken one Button and a TextView on screen. You can see XML code in below screen.


I have used Linear Layout with vertical orientation to design it.

2. Add or create resources
Here in this program I have created some resources which you can see in below screen.

3. Write Class File
 For this design we have a class file to access and code for controls in layout. Take a look at below screen.


Here I have taken a class named Counter which extends Activity class. int counter = 0; is used to count number of clicks on button.

In the method onCreate objects of Button and TextView is created. findViewById(R.id.btn_click) is a method which fetch control from layout and we cast this to button object. Class R is used to access resources of your project in your Java file. Here Button is a View in layout and we are accessing it with R.id.btn_click.

After creating objects I have written an OnClickListener method for button. After writing this event, each time you press button this event will fire. In this listener method I have incremented counter.

I have written this program to make you understand findViewById and OnClickListener method. 

View findByViewById(int id) is method of Activity class which looks for child view with given ID.  If id found it will return View which ultimately casted to respective object.

setOnClickListener(OnClickListener ocl) is a method of button object which executes every time button pressed.

Thats it. You're done!!!

Friday, August 24, 2012

Activity. What is that???

Android application can constructed for many purpose. It can be an activity, a service, a broadcast receiver or can be content providers. So lets get some focus on Activity.

Activity: An activity is a single, focused thing that user can do. User interacts with all activities in an android phone, so the Activity class takes care of creating a window in which user can place UI with setContentView(view). Activities are presented to user in many ways like, Full screen windows, Floating windows, or embedded inside another activities.

The Activity class is an important part of an application's overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform's application model.

Now, lets understand Application fundamentals.

1. Each screen in an Android application is an activity, and user can perform actions by interacting with visual components on the activity. It is like a web site where you can perform some actions on one page but you have to move to another page to access components of that page.

2. Each activity in an Android application is a direct subclass of Activity base class or a subclass of an Activity subclass that provides specialized functionality, and is represented in the application package as a single Java class.

3. All activities in application must be defined in AndroidManifest.xml file (We'll learn it in detail), an XML file that keeps all the information of your Android application like, components, resources, and permissions that make up the application.

4. All Android application components, including activities, have lifecycles. The current lifecycle state of a component provides part of the information the Android OS uses when it determines what components can be safely removed from memory in order to free up memory space. All activities inherit a set of lifecycle methods from the Activity base class that are executed when the corresponding lifecycle state of the activity is reached.

 Take a look at Activity life cycle.
http://developer.android.com/reference/android/app/Activity.html 


Above digram directly linked from official website of Android.

onCreate() :
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
onRestart() :
Called after your activity has been stopped, prior to it being started again. Always followed by onStart().
onStart() :
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
onResume() :
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
onPause ():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
onStop():
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

onDestroy() :
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.


When the Activity first time loads the events are called as below:
          1. onCreate()
          2. onStart()
          3. onResume()

When you click on Phone button the Activity goes to the background & below events are called:
          1. onPause()
          2. onStop()

Exit the phone dialer & below events will be called:
          1. onRestart()
          2. onStart()
          3. onResume

When you click the back button OR try to finish() the activity the events are called as below:
          1. onPause()
          2. onStop()
          3. onDestroy

Activity states
The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:

These states can be broken into 3 main groups as follows:

Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.

Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.

Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.

Sunday, August 19, 2012

Let's have a look at code...

In previous articles you learned how to create a project in Android. We have seen that, how to create a Hello World program in Android but, we haven't look for the code of the project. Let's understand each file which play important role in making of an Android Project.

Any Android project can be created in three simple steps.

1) Design your screens with controls.
2) Add or create resources in your project.
3) Write class files.

We'll understand Hello World program in same manner.

1) Design screen : To design your screen you have to go to /res/layout/activity_hello_world.xml which represent you screen layout. Name of this XML file inherit from activity name you have given at the time of project creation.

Graphics layout window of activity_hello_world
This is layout of Hello World application design. On the screen there is only one TextView control having caption with "Hello World!". What ever you design on this screen, the XML code for the design will generate and store in XML file. Here in this example it will store in activity_hello_world.xml.

In the bottom side of the above screen there are two tab given. One is Graphical Layout and another is activity_hello_world.xml.


Above screen is XML window of Hello World project.

Everything in the design should be in layout. Here I have used RelativeLayout. In this layout I have put a TextView control which displays some text.

Each control in design have some attribute to set like, ID, TEXT, WIDTH, HEIGHT as you can see in screen shot. Now, I am finished with design and I have to move to next step which is creating some resources.


2) Create Resources : In this step I'll create some resources but, before that let me explain what exactly resource in Android project.
In small window you can see list of resources you can create. Here in Hello World program I have created some String resources. String resources can be created in strings.xml file with <String></String> tag. Take a look at below screen.
You can see in above screen that there are some strings created with <String> tag and given some Name and Values. You can access these strings anywhere in your Android project in many ways, like in layout file you can use @string/id and you can use these in Java file with use of R class.

Now, resources are ready. Time to go for last step.

3) Write class files : This is the part where main logic of your project exists.All Listener events, Database actions and Control events you'll write here.
You can see HelloWorld.java file code in above screen. Class name is Hello World which extends Activity class. I'll explain in detail about Activity in near future. You just need to understand that for each screen in your application you'll need one class which extends Activity class.

As you can see there are two methods named onCreate and onCreateOptionsMenu. We have to concern with onCreate method for now. This method will call when your Activity runs on the screen. Means, when you run your project or run application in your mobile this method will call. Each Activity has its own onCreate method. You can write code here that you want to run when Activity starts.

OnCreate method has two line already coded.
1. super.onCreate(savedInstanceState) which calls Activity class' onCreate method.
2. setContentView(R.layout.activity_hello_world) which sets activity_hello_world.xml as layout of your Hello World activity.

Thats it, you are done with code of this project!!!

Monday, August 13, 2012

Directory Structure of Android Project in Eclipse...

Every single project in Eclipse has some predefined directory structure which Eclipse creates on behalf of us. Android project has also its directory structure which may different in different version of Eclipse. The structure explain here is from Eclipse JUNO which is latest one.


Above is the structural view of any Android project in Eclipse. I'll explain each one by one.

1) SRC : SRC is a folder where main source code of your project exists. All your packages and class files reside in this folder.

2) GEN : GEN is a folder where R.java file resides. All the resources in your project like images, strings, sounds, videos you can access in your source code or java file using R.java.

3) Android 2.2 : Its is a folder where jar file for the particular version of android exist.

4) RES : In this folder all the resources located. All strings, images, values etc.

5) DRAWABLE : In this folder all your images required in the project stored. It has four different folder for different resolution display. Drawable-hdpi is for High Density Pixel displays, Drawable-mdpi is for Medium Density Pixel displays and so on.

6) LAYOUT : This folder holds all XML file for your all activities. There are individual XML file for each activity. You can drag and drop controls on the layout, change properties of controls. Ultimately this is your design hub for your Android project.

7) VALUES : This folder holds some XML files for other resources like string, color etc. 

8) AndroidManifest.xml : This is the main configuration file of any Android project. All the activities, filters, services must inform AndroidManifest.xml file. This file has all the information of your project and your application.

Thats is. This is all you need know to understand any Android project.
          

Saturday, August 11, 2012

Say HELLO WORLD!!!!!

We done with some tuts on installing Android, now its time to have some action. I'll start with Hello World Application which actually is by default application in Android with Eclipse. Though I'll explain each step with its reason for existence.

Follow below steps to make Hello World Application.
[Note: The project creation screens may differ with version of Eclipse. I have used Eclipse JUNO here which is latest one.]

1. Go to File -> New Project.
2. Select Android Application Project as shown in below image.
3. Give Application and Package name, select prefer version of SDK.
4. Next screen is to choose icon for your application. You can select your PNG file or can select from given list by clicking Choose button.
5. Now select Blank Activity and click next.
6. Give name of Activity and Layout. Click Finish.
 

Its done. Your project is created and you can see it in your Project Explorer windows.
To run the project right click on your project in project explorer, go to Run -> Android Application as shown in image below.



Don't have Internet? Try this!!!!

Besides my first post, you can install all softwares offline. Only thing you need to download Eclipse, ADT Plugin and Andoid SDK manually. After having all these packages you can install it on your PC without Internet.

Download eclipse : Download Eclipse
Download SDK : Android SDK
Download ADT : ADT 20.0.2


Follow below instruction for offline installation.

1. Start eclipse.
2. Go to Help -> Install New Software.
3. Click Add button (It will start new window to add repository)
4. Click on Archive and select ADT plugin RAR file.
5. After clicking OK, in available software dialog select the checkbox next to Developer Tools and click Next.  
6. In next window you'll see list of tool to be download. Click Next.
7. Accept the agreement and click Next.
8. After completion of installation just restart Eclipse.
9. Now extract Android SDK.
9. Go to Windows -> Preferences and select Android from left hand side list.
10.  Select SDK Location where you have extracted the ANdroid SDK. Click Apply and OK.

Thats it, you are done !!!!!

Prepare Ingrediants for Android Development!

Android is the most complete and free operating system for stand alone device. If you are good at Core Java and have lil bit knowledge of XML, you can start development in Android.

All you need is an eclipse the classic version, Android SDK (version which ever you want, 2.2 & 2.3 preferred) . Just follow below steps to install all tools you need for development. Actually all softwares are portable so it is just copy paste like.

Download eclipse : Download Eclipse


Follow below instruction online installation.

1. Start eclipse.
2. Go to Help -> Install New Software.
3. Click Add button (It will start new window to add repository)
4. In Name text box enter name what ever you want.
5. In location field enter URL.
      https://dl-ssl.google.com/android/eclipse/
[Note: If there is any problem acquiring plug-in try using "http" instead of "https".]
6. After clicking OK, in available software dialog select the checkbox next to Developer Tools and click Next.
7. In next window you'll see list of tool to be download. Click Next.
8. Accept the agreement and click Next.
[Note: If you get security warning saying that authenticity or validity of the software can't be established. Click Next.]
9. After completion of installation just restart Eclipse.

The above process will install ADT (Android Development Toolkit) on your machine. Still you need to install Android SDK to start development.

10. After completion of above process you'll get an option in Window menu named "Android SDK Manager". Clicking on that option will open Android SDK Manager for you.
11. Select Android versions from list you want to install and click on Install Packages. It will open new window which will display all packages you are going to install.
12. Select Accept All and click Install, which will start download of Android SDK  for you.

After completion of downloading just restart Eclipse. Thats it, you are done !!!!!

You can suggest or query in case if you face any trouble in above process.