android intent communication

Android Intents: Explicit and Implicit Intents

What are Intents In Android?

An intent is an abstract description of an operation to be performed. It is a passive data structure holding an abstract description of an action to be performed. It can be used with startActivity() to launch an Activity, sendBroadcast() to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service. Use Intents to communicate between 2 components in Android.

android intent communication

slidenerd.com

1) Starting An Activity With Intents

  • Start a new instance of an Activity by passing an Intent to startActivity().
  • The Intent describes the activity to start specifying its name directly or specifying some other parameters (explicit and implicit intents which we’ll see shortly) and carries any necessary data.
  • To receive a result from the activity when it finishes, call startActivityForResult() inside your first Activity from where you originally created an Intent to start the second Activity.
  • Your activity receives the result as a separate Intent object in your activity’s onActivityResult() callback.

2) Starting A Service With Intents

  • A Service is a component that performs operations in the background without a user interface.
  • Start a service to perform a one-time operation by passing an Intent to startService().
  • The Intent describes the service to start specifying its name directly or specifying some other parameters (explicit and implicit intents which we’ll see shortly) and carries any necessary data.

3)To trigger a Broadcast Receiver

  • A broadcast is a message that any app can receive.
  • The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging.
  • You can deliver a broadcast to other apps by passing an Intent to sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast().

Intent Types: Explicit And Implicit

Explicit Intents:

  • Specify the fully qualified class name of the Service, Activity or Broadcast Receiver that you wish to start from your component (Activity/ Service/ Broadcast Receiver).
  • Explicit Intents are used within your app to start some component, because the name of the component that you want to start is known in advance.
  • For example, start a new activity in response to a user action or start a service to download a file in the background.
  • When you create an explicit intent to start an activity or service, the system immediately starts the app component specified in the Intent object.

Implicit Intents:

  • You don’t know the name of the component to invoke since it may be a part of some other app package.
  • In this case you access the component by specifying a String known as ACTION. 
  • For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map.
  • When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent you created to the intent filters declared in the manifest file for the component which you want to invoke.
  • If the intent matches an intent filter, the system starts that component and delivers it the Intent object.
  • If multiple intent filters match with your Intent object, the system displays a dialog so the user can pick which app to use.

How To Create Explicit Intent?

  • An Explicit Intent object carries information that the Android system uses to determine which component to start which includes the following pieces:
    • Name of the Component who will be activated
    • Any Extra data that should be sent to that Component (Activity/ Service /Broadcast Receiver)
  • An Intent is explicit if it specifies the component name, otherwise it is implicit.
  • For an explicit Intent, the name of the target component is sufficient to determine which Component should be started.
  • Always use Explicit Intents to invoke Services since an implicit Intent used to invoke a Service may trigger some other Service on your device that can respond to that Intent and cause some undesirable work to be executed by that Service in the background since the user cannot see which Service was started.

Example

  • To create an explicit intent, define the component name for the Intent object and all other Intent properties are optional.
  • The Intent(Context, Class) constructor requires the a reference to the Context object which is directly written as ‘this’ inside the Activity and a reference to the target Class object that you want to call.

How To Create Implicit Intent?

  • If you don’t specify the component name that you want to activate, the Intent becomes implicit.
  • Your app cannot perform certain actions, however there are other apps that can perform them, for example: reading a QR Code.
  • In this case, your app calls the other app and supplies the data on which the other app should perform the action, for example: the QR Code image from which you want to extract data and the other app does this accurately and returns the results.
  • An Implicit Intent has 4 parts where you must specify one or more to find the list of components who can perform your task (Activities/Services/Broadcast Receivers).
    • Action
    • Data
    • Category
    • Extras

Action: 

  • A String that specifies the action that you want to perform such as View or Pick (For Activities and Services) or specifies the action that was performed such as Boot-up of your device in case of Broadcast Receiver.
  • Android defines a number of predefined ACTIONS through their APIs and also lets you define your own ACTION Strings.
  • Example Predefined Action:
  • ACTION_VIEW
  • Defined as a public static constant within the Intent class
  • Used as an ACTION with Activities when the calling Activity wants to display some piece of information such as a photo to view in a gallery app, or an address to view in a map app and there may be a target Activity that can perform this ACTION
  • ACTION Strings are defined in different Android classes such as Intents, Settings and other API classes.
  • Example Custom-Defined Action:
  •  If you define your own actions, be sure to include your app’s package name as a prefix.

Category:

  • A String specifying extra information needed to determine who should handle this Intent.
  • Android defines a number of predefined categories and you can also define your categories which is rather uncommon.
  • Example Predefined Category:
  • CATEGORY_BROWSABLE
  • The Activity that declares this category in its IntentFilter in the Manifest is treated as an Activity that lets itself be used by the Web browser to display an image or a link.
  • CATEGORY_LAUNCHER
  • The Activity that declares this category in its IntentFilter in the Manifest is treated as the initial Activity or Main Activity for that particular app and is displayed in the Launcher Screen where all the apps are placed.

Data:

  • A Uri Object that references the data to be acted on and/or the MIME type of that data.
  • The Intent’s action is sufficient in most cases to understand the type of data it would work with.
  • For example, if the action is ACTION_EDIT, the data should contain the URI of the document to edit.
  • Specify the MIME type of data along with its Uri.
  • An activity that’s able to display images probably won’t be able to play an audio file, even though the URI formats could be similar.
  • So specifying the MIME type of your data helps the Android system find the best component to receive your intent.
  • For Content Providers, the MIME type can sometimes be inferred from the URI since it begins with content://.
  • To set only the data URI, call setData().
  • To set only the MIME type, call setType().
  • You can set both explicitly with setDataAndType().
  • If you want to set both the URI and MIME type, do not call setData() and setType() because they set the value of the other parameter (type in case of setData() and data in case of setType() to null).
  • Always use setDataAndType() to set both URI and MIME type.

Extras:

  • Additional data needed to accomplish the task can be sent along with the Intent in the form of key-value pairs.
  • Some actions require EXTRAS.
  • Either use the putExtra() methods to specify key-value pairs or use a Bundle object which contains all the extra data and add the Bundle using putExtras().
  • For example, when creating an intent to send an email with ACTION_SEND, you can specify the “to” recipient with the EXTRA_EMAIL key, and specify the “subject” with the EXTRA_SUBJECT key.
  • To declare your own EXTRAS, use the package name as shown below

 Flags:

  • Supplied at the time of creating Intents.
  • Act as metadata defining certain things such as
    • Under which task should the Activity be launched inside?
    • Should this Activity be included in the recent list of launched Activities?
  • Use the setFlags() method to control such aspects.

 Example

  • An implicit intent specifies an action that can invoke any app on the device able to perform the action.
  • For example, if you have content you want the user to share with other people, create an intent with the ACTION_SEND action and add extras that specify the content to share.
  • When you call startActivity() with that intent, the user can pick an app through which to share the content.
  • Sometimes the user won’t have any apps that handle the implicit intent you send to startActivity().
  • If that happens, the call will fail and your app will crash.
  • To verify that an activity will receive the intent, call resolveActivity() on your Intent object.
  • If the result is non-null, then there is at least one app that can handle the intent and it’s safe to call startActivity().
  • If the result is null, you should not use the intent and, if possible, you should disable the feature that issues the intent.
android intent chooser

slidenerd.com

  • When startActivity() is called, the system examines all of the installed apps to determine which ones can handle this kind of intent (an intent with the ACTION_SEND action and that carries “text/plain” data).
  • If there’s only one app that can handle it, that app opens immediately and is given the intent.
  • If multiple activities accept the intent, the system displays a dialog so the user can pick which app to use.
  • When there is more than one app that responds to your implicit intent, the user can select which app to use and make that app the default choice for the action.
  • If the user wants to use the same app, such as the same web browser to open that document, then there are no issues.
  • If multiple apps can respond to the intent and the user might want to use a different app each time, you should explicitly show a chooser dialog.
  • The chooser dialog asks the user to select which app to use for the action every time (the user cannot select a default app for the action).
  • To show the chooser, create an Intent using createChooser() and pass it to startActivity().