Saturday, May 16, 2015

Android Intent

Android Intent: Android intent is a object which carrying an intent or message from one component to another component inside an application or outside the application. Android intent is a communication medium between any android core components- services,activities and broadcast receivers.

We can use android intent to send data from one activity to another activity with application. Android intent used while to call native android services from our application like calling camera, web browser, calender or any other native android service.



Intent Types:  There are two types of intent
  • Explicit Intent: Explicit intent specify the component to start by name directly because we already know the component name that we have to call. We mostly use this intent to start the component in our own application. For example to start a new activity on user request we directly specify the activity name in intent object.
     
    // Explicit Intent by specifying its class name i.e SecondActivity.class
    Intent i = new Intent(this, SecondActivity.class);
    // Below we are sending two parameter from one activity or screen to another activity or screen 
    i.putExtra("Param1", "ABC");
    i.putExtra("Param2", "123");
    
    // Starts Second Activity
    startActivity(i);
    
    Then the second activity must invoke method getExtras() to receive the parameter data sent by first activity as shown below 
     
    // Get bundle object in your second activity code
    Bundle extras = getIntent().getExtras();
    // Extract data using passed keys as described by first activity i.e Param1 and Param2
    String value1 = extras.getString("Param1");
    String value2 = extras.getString("Param2")

  • Implicit Intent: Implicit intent does not specify the name of component directly instead it specifies the action name which we have to perform which allows a component from another app to handle it. For example if we have to take photo in our app so instead of making camera functionality in our app we can use native android camera to catch the photo using implicit intent. 
     
    // Below intent code opens web url www.google4tech.com in another application  
    Intent intent=new Intent(Intent.ACTION_VIEW);  
    intent.setData(Uri.parse("http://www.google4tech.com"));  
    startActivity(intent);
    

So like this we can use intent in our android application to use android system native functions using implicit intent and to communicate between different android component (Activities,Services and broadcast receivers) using explicit intent.

Thanks for visit and reading the article. We will post more android related article soon. Please give your valuable feedback.

0 comments:

Post a Comment