Android Intent | Complete Tutorial with Example

Apart from the four Android components there is one more basic concept in Android which every beginner in Android Development should be aware of. The concept of Android Intent. Intents are used to request any action/operation from any android component of the same application, another application on the device. For example, consider you want to click a  picture in your application. Intents enable you to simply request camera app to click a picture and deliver the picture back to your application. They basically connect Android components with each other. Android defines Intents as the following

An Intent is a messaging object you can use to request an action from another app component.

The most common use of Android Intent is to start any of the three most important components in Android- Activity, Service, BroadcastReceiver

  • Activity
    You can start activity by calling startActivity(Intent) and passing an intent describing the target activity
  • Service
    Similar to Activities, Services can also be started using startService(Intent) and passing an Intent describing the Service
  • BroadcastReceiver
    Broadcasts are also delivered using Intents. You can notify other apps of any event by sending Broadcasts from your app using sendBroadcast(Intent) and passing the Intent describing the event.

 

Building an Android Intent

Android Intent object is a passive data structure holding abstract description of the operation to be performed. Basically it carries information describing the operation to be performed, this information is used by the Android System to decide which Component will handle the Intent. You can even bundle data which will be used by the receiving component to perform the operation along with the Intent.

Public Constructors

  • new Intent()
    Create an empty intent.
  • new Intent(String action)
    Create an intent with a given action.
  • new Intent(String action, Uri uri)
    Create an intent with a given action and for a given data url.
  • new Intent(Context context, Class<?> cls)
    Create an intent for a specific component.
  • new Intent(String action, Context packageContext, Class<?> cls)
    Create an intent for a specific component with a specified action and data.

Action

This is a string which names the action to be performed. You can use this to describe the action to be performed by the Intent. Android has list of predefined actions which can be used to describe many generic operations. Such as if the purpose of the Intent is to do a web search than the Action should be ACTION_WEB_SEARCH. The action largely determines what information is bundled along with the intent object. For example if the the Intent action is ACTION_WEB_SEARCH then you will sending URL of the web page/text to do a web search along with Intent.

Action is set by calling setAction() on the Intent object as shown below

Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"text_to_search");
startActivity(intent);

Category

Category is a string describing the kind of components this Intent should be handled by. This is optional information passed with an Intent which helps Android System to resolve which app component it should start. Similar to Action, Android has a predefined list of Categories which can be passed with your Intent to describe the target component. You can consider this scenario for example, if the user is viewing a web page or an e-mail and clicks on a link in the text, the Intent generated to execute that link should be passed with CATEGORY_BROWSABLE , so that only activities supporting this category will be considered as possible actions.

You can add category to your Intent by simply calling addCategory() on the Intent object as shown below

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
browserIntent.addCategory(CATEGORY_BROWSABLE);
startActivity(browserIntent);

Extras

Extras are key-value pairs sent along with the Intent to send additional information to the receiving component. This extra information is in most cases required by the receiving component to perform the requested operation. You can add any value (Boolean, Integer, String, Bundle etc) along with a String key using the putExtra() API to the Intent object. For example, notice how we pass the “search query” along with ACTION_WEB_SEARCH using the putExtra() API.

Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"text_to_search");
startActivity(intent);

Flag 

Flags are optional information passed along with an Intent. They instruct the Android System how to launch the component receiving the intent and how to treat it after its launched. Android has a predefined list of Flags any of which can be added to an Intent object by calling addFlag() on the Intent object. For example in the code snippet below we add the flag , this ensures that the new component which receives this intent is started in a new task.

Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, stringBuilder.toString());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)

Data/ Type

This is to specify the URI of the data to be acted on. For example if the the Intent is for editing an Image then you can pass URI of the image by calling setData() on the Intent object.  This is often used used with setType() which used to specify the type(MIME type) of data bundled with the Intent. Specifying both data and type along with the Intent will help the Android system in selecting the proper app component for it. If you want set both data and type for an Intent use setDataAndType()  instead of setData() and setType() seperately because they cancel each other.

A very simple example for this would be starting an Intent to view a Image file. Here apart from setting the action as ACTION_VIEW we set the Data as the file URI and type as “image/*”. This informs Android System that file URI passed is an image and hence it selects only components which can display an image.

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);

Sending an Android Intent

Above we saw different kinds of information which can be bundled along with Android Intent. Based on this information Android decides which app components it should start

Explicit Intent

This is for cases where you know what your target component is. Here you directly specify the target component package/class name using the setComponent() API or use the public constructor. Android just resolves the package/ class name and directly opens the target component(if it is present on the device). This is mostly used for starting components in the same application, because you are sure that the present  on the device.

For example , in the code snippet below we start an activity by just naming the activity class.

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);  
intent.putExtra("Value1", "Android Tutorial");  
intent.putExtra("Value2", "AndroidClarified");  
startActivity(intent);

Implicit Intent

Implicit Intent do not specify the target component but instead describe the operation to be performed. The operation is described with the help of setAction(), setData() and various other APIs mentioned above. Android System which receives the Intent, scans the device for all the components which can handle this Intent. If multiple components are able to handle the intent on a single device then it opens a dialog where user can select the component. Else It directly launches the selected component.

For example your application sends an Intent with ACTION_VIEW and a webpage URL, Android system will select all the browsers on the device and launch a dialog for the user to select any one browser. If only one browser is present on the device then it directly launches it.

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
browserIntent.addCategory(CATEGORY_BROWSABLE);
startActivity(browserIntent);

 

android intent chooser
Intent Chooser

 

Conclusion

This finishes the basics about Android Intent. If you liked this tutorial please share it with your friends and feel free to comment in case of any confusion.

If you want learn more about basics in Android Development read this

Android Example : Alarm Manager Complete Working

AlarmManager as the name itself suggests is used to schedule time based operations outside the lifecycle of your application. With the help of AlarmManager you can schedule your application to run at any scheduled time in future. Once the scheduled time arrives the target application starts running even if the device is asleep.

Photo_1521975251900

Continue reading

Android Example : Fetching Current Location with FusedLocationProviderAPI

marker

 

Fetching Location is one of the most useful features on mobile devices. In fact lot of apps completely rely on user’s location for their business, take Uber for example. This implies that it is very important to fetch user’s location accurately and seamlessly on mobile devices. In Android there are basically two methods to fetch user location

Android framework location APIs were the most reliable way of fetching location up until FusedLocationProviderApi was released. Fused location provider is found to be more accurate, fast and easy to implement. Above all Android doc itself encourages developers to migrate to Fused Location provider.

Continue reading

Android Broadcast Receivers with Example

What are Broadcasts?

Consider a situation in which you are downloading a large file in your app and suddenly the battery goes critically low , you don’t want the download to stop abruptly and would like to show the user a notification/dialog so that he can pause the download.  Creating a service just to keep on checking the battery power would be too much work for a simple notification. What if the android system itself notifies you of any such system event like battery low or airplane mode.

Guess what?  It does!. And you can handle these events very efficiently.. These events are known as broadcasts and you need to handle them in a broadcast receiver. Your app can have its own custom broadcasts which it can send within the app or to other apps on the device to notify them of an event they might be interested in.

One common use case of  sending broadcasts within the same app is mentioned here:

Suppose you have updated your  profile details in an activity inside the app, you would like the updated changes to be reflected immediately in all the other active activities without having to refresh them. In this case you can send a broadcast informing the other activities that the profile details are updated

Continue reading

BroadcastReceiver in Android | With Example

BroadcastReceiver is one of the four basic Android Components. In this example we will be learning how to create a BroadcastReceiver and listen for broadcast. Before that let us first understand what are Broadcasts

What are Broadcasts?

Consider a situation in which you are downloading a large file in your app and suddenly the battery goes critically low , you don’t want the download to stop abruptly and would like to show the user a notification/dialog so that he can pause the download.  Creating a service just to keep on checking the battery power would be too much work for a simple notification. What if the android system itself notifies you of any such system event like battery low or airplane mode.

Guess what?  It does!. And you can handle these events very efficiently. These events are known as broadcasts and you need to handle them in a broadcast receiver. Your app can have its own custom broadcasts which it can send within the app or to other apps on the device to notify them of an event they might be interested in.

One common use case of  sending broadcasts within the same app is mentioned here:

Suppose you have updated your  profile details in an activity inside the app, you would like the updated changes to be reflected immediately in all the other active activities without having to refresh them. In this case you can send a broadcast informing the other activities that the profile details are updated

Continue reading

Android Service-LifeCycle and Working | With Example

 

Ever wondered how a song that you started on your music app plays even after you have killed the app? Well, this happens because of service. Service is a indefinitely running background operation without an UI .Google explains service as

A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

Continue reading

How to develop your first Android App?

Hey everyone, so far we got ourselves introduced with Android architecture and its four basic components. So why not start developing a “Hello World” Android app? Here it is!

firstandroidapp

Continue reading

Develop your Hello World Android App

Hey everyone, so far we learnt about  Android architecture and its four basic components. So why not start developing a Hello World Android app? Here it is!

firstandroidapp

Continue reading

Android Development System Requirements

system-configuration

About 85% of the world’s smartphone run on Android. Android SDK is available for free. Many App developers have turned into millionaires overnight. I don’t think you need any other reason to learn Android development. But first you need to set up an environment for developing. Today we will be discussing what are the basic Android Development system requirements.
Continue reading

Android Components:Four pillars of every Android app

Before beginning with the actual app development it is very important for every developer to be aware of the four Android Components. These are building blocks of an Application. Any feature that we see in an app is the result of interaction between these components.A developer needs to declare all the components he is using inside the AndroidManifest.xml, this what informs the system of number and names of components used in this app.

The four components are

  • Activity
  • Service
  • Content providers
  • Broadcast Receivers

Continue reading