Basics of Intents In Android


One of the many words that confuse beginners in Android is Intents . Here in this tutorial, we are going to discuss what Intent is and use it in real application to explain clearly what it is. Also, You will also get basic information about Activity’s life cycle and Design library, because i have written code of this tutorial in Design Support library itself. So lets get started.
In simple words, Intent is a simple object which you can use to request an action from another app or app’s component. There are three fundamental use-cases of it.
To start an Activity:
You can start new activity and pass some data from one app to another app using Intent. The Intent describes the activity to start and carries any necessary data. Also, if you want to receive result from the activity when it finishes, call startActivityForResult() and I will explain this later via sample code later in this tutorial.
To start a Service :
A service is a component that performs operations in the background without User-Interface. You can start service via Intent to perform one-time operation. For example, downloading a file and you can specify service via startService() method.
To deliver a broadcast :
A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as device starts charging. You can deliver a broadcast to other apps by Intent.
There are mainly two types of Intent :
1. Explicit Intent:

To open the component/activity or service of your own app. you need to pass fully qualified class name during this process.For example, ActivityA has a button which will open ActivityB upon pressing that button.

2. Implicit Intent :
do not specify a specific component, but instead declare a general action to perform, which allows component from another app to handle upon data sent by Intent. When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use.
There are some little small details that you should know, which you can read from here Building an Intent.

Tutorial

In this tutorial, i am assuming that you are already familiar with basic Android such as how to inflate layout and create views. So lets get started on how to create intent. The image below shows how exactly our User-Interface would look like. I have made it clear and as simple as possible.



1. Enter your address and Open Address in Google Maps

So code below is to create how to create implicit intent with “PICK” action. It means that this Intent will choose app itself from the data we have given to it.




 // Initialize UI elements
final EditText addrText = (EditText) findViewById(R.id.location);
final Button button = (Button) findViewById(R.id.mapButton);

// Link UI elements to actions in code
button.setOnClickListener(new View.OnClickListener() {

// Called when user clicks the Show Map button
public void onClick(View v) {
try {

// Process text for network transmission
String address = addrText.getText().toString();
address = address.replace(' ', '+');

// Create Intent object for starting Google Maps application
Intent geoIntent = new Intent(
android.content.Intent.ACTION_VIEW, Uri
.parse("geo:0,0?q=" + address));

// Use the Intent to start Google Maps application using Activity.startActivity()
startActivity(geoIntent);

} catch (Exception e) {
// Log any error messages to LogCat using Log.e()
Log.e("TAG", e.toString());
}
}
});
}
Here, we have two views which you can see in the above code. One is textView and another is button. We are initializing the views as follows

       final EditText addrText = (EditText) findViewById(R.id.location);
final Button button = (Button) findViewById(R.id.mapButton);
Upon entering address, I have implemented onClick() method which will enable button to trigger action.Get the value of address from TextView by adding
  String address = addrText.getText().toString();
address = address.replace(' ', '+');
//addrText is a textView and you can get its value via .getText() method.

You can create Intent to choose “PICK” OR “VIEW”.

PICK : This specifies that Intent will choose the app from your device. You can specify this by “ACTION_VIEW”.

VIEW : This will show you all the application that can handle such data and let’s user decide what to do with Intent data. You can specify this action by “ACTION_SEND”.

In this first part, we are creating Intent using “PICK”, which means that we Enter the address and decide to open google maps. We don’t want user to select any other apps.

Intent geoIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri
.parse("geo:0,0?q=" + address));
android.content.Intent.ACTION_VIEW : Activity Action: Display data to the user. This is the most common action performed on data – It is the generic action you can use on a piece of data to get the most reasonable thing to occur. It is commonly a “PICK” action, where app will itself open app that most reasonable.
Uri.parse : A Uri object is usually used to tell a ContentProvider that we want to access by reference. It is an immutable one-to-one mapping to a resource or data. The method Uri.parse create a new object from a properly formatted string. This is the data passed to Intent and it must be passed using Uri object. There are some of the Common Intent which are important to know.
You can finish creating intent process by following method

startActivity(geoIntent);  
//To start any Intent : startActivity(IntentObject);

Implicit Intent – Let User decide which app to open to handle data


This are “SEND” type of intent. It lets the user to pick an application to open. This can be achieved using “ACTION_SEND”. Also known as the “share” intent, you should use this in an intent with startActivity() when you have some data that the user can share through another app, such as an email app or social sharing app. The image on right side shows us how it gives all the app that can open such data we pass in intent.

To create implicit Intent with SEND, you can do as follows (read my comments to understand) 




//Button onClick method
    public void implicitSendText(View v){

        //Create intent object
        Intent intent = new Intent();
        // setAction - Set the general action to be performed.
        intent.setAction(Intent.ACTION_SEND);
        //putExtra - method to send a data in this case we are sending Intent.EXTRA_TEXT as "Hello from Codemeaning.com
        intent.putExtra(Intent.EXTRA_TEXT, "Hello From CodeMeaning.com");
        //You have to specify type of data you are passing. 
        // www.freeformatter.com/mime-types-list.html will give you detailed information about this types.
        // for example, simple text file can be typed as "text/plain" 
        intent.setType("text/plain");

        // Verify that the intent will resolve to an activity
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent); // TO start an Intent
        }

    }



Explicit Intent - Specify Exactly what app to use to opent the Intent


An explicit intent is one that you use to launch a specific app component, such as a particular activity or service in your app. To create an explicit intent, define the component name for the Intent object—all other intent properties are optional.
As i mentioned before, explicit intent are to open specific component or service of your own app. In the app as a part of this tutorial, have two activities. I have used Explicit intent to open ActivityB using button from ActivityA.
 
 

//Button onClick method
    public void explictButton(View v){

        //Specify which activity you want to open. in this case ActivityB.class
		
        Intent intent = new Intent(this, ActivityB.class);

        // Verify that the intent will resolve to an activity
		
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }

    }



From this above picture, when you press explicit intent , it will transfer you on this screen...


As you can see in the images above, using explicit intent, i have opened ActivityB. This is known as Explicit intent. I hope this made you clear your confusion.which means, You have explicitly specified intent, that using this intent , i want to explicitly open this ActivityB only.

I hope this tutorial helped you to understand what Intent is all about. Please comment if you have any confusion or any suggestion of how can i improve it.
The full app is in my repository. click here to download full app tutorial about Intent 
The code is properly documented, so all of you readers can understand easily.
Happy Coding!
Enjoy.

References :

Post a Comment

0 Comments