Why intent in android




















An intent contains certain header data, e. Optionally an intent can also contain additional data based on an instance of the Bundle class which can be retrieved from the intent via the getExtras method. You can also add data directly to the Bundle via the overloaded putExtra methods of the Intent objects. The key is always of type String. The receiving component can access this information via the getAction and getData methods on the Intent object. This Intent object can be retrieved via the getIntent method.

The component which receives the intent can use the getIntent. That is demonstrated in the following code snippet. An activity can be closed via the back button on the phone.

In this case the finish method is performed. If the activity was started with the startActivity Intent method call, the caller requires no result or feedback from the activity which now is closed. If you start the activity with the startActivityForResult method call, you expect feedback from the sub-activity. Once the sub-activity ends, the onActivityResult method on the sub-activity is called and you can perform actions based on the result.

In the startActivityForResult method call you can specify a result code to determine which activity you started. This result code is returned to you. The started activity can also set a result code which the caller can use to determine if the activity was canceled or not. The sub-activity uses the finish method to create a new intent and to put data into it. It also sets a result via the setResult method call. The following example code demonstrates how to trigger an intent with the startActivityForResult method.

If you use the startActivityForResult method, then the started activity is called a sub-activity. If the sub-activity is finished, it can send data back to its caller via an Intent. This is done in the finish method. Once the sub-activity finishes, the onActivityResult method in the calling activity is called. Intents are used to signal to the Android system that a certain event has occurred. Intents often describe the action which should be performed and provide data upon which such an action should be done.

For example, your application can start a browser component for a certain URL via an intent. This is demonstrated by the following example. A component can register itself via an intent filter for a specific action and specific data. An intent filter specifies the types of intents to which an activity, service, or broadcast receiver can respond to by declaring the capabilities of a component. Android components register intent filters either statically in the AndroidManifest. An intent filter is defined by its category, action and data filters.

It can also contain additional meta-data. If an intent is sent to the Android system, the Android platform runs a receiver determination.

It uses the data included in the intent. If several components have registered for the same intent filter, the user can decide which component should be started. You can register your Android components via intent filters for certain events. If a component does not define one, it can only be called by explicit intents.

This chapter gives an example for registering a component for an intent. The key for this registration is that your component registers for the correct action, mime-type and specifies the correct meta-data.

If you send such an intent to your system, the Android system determines all registered Android components for this intent. If several components have registered for this intent, the user can select which one should be used. The following code will register an Activity for the Intent which is triggered when someone wants to open a webpage. The following exercise demonstrates the usage of intents to start a sub-activities and how exchange data between them.

Create or reuse a new Android project with the com. This application has an activity called CreateUserActivity. For the following layout, only the text widget labeled Practice and the text widget for the user name is used. Feel free to reduce the layout to this. Add the new activity to the AndroidManifest. Ensure that this is the main entry point for the user via the intent-filter. The CreateUserActivity activity cannot be started anymore by the user directly.

In the finished version of the app, you would of course persists the user and reload it. In this case the create user activity would only be started if no user was found.

The following code gives some pointers on how to solve this. Add another activity called LearnActivity to your application. This activity should allow to practice some math. Use the following screenshot as inspiration and build a similar user interface. In Android you frequently add the implementing class as callback class. This can be useful if you have lots of buttons. For example, to register your activity as callback for the view, you can use the following snippet.

Allow to start this activity from the UserOverviewActivity via the Practice text view. Pass the user name and its current skillPoints as extra data to it. In the learn activity get the Bundle with the intent data via the getIntent. Get the value of the passed extra with the extras. Once finished return the new skillPoints to the calling application.

If the skillPoints have increase by 10 points, show a Toast from the UserOverviewActivity to the user with a positive message. This allows you to use the onActivityResult method to receive data from the sub-activity. Extract the extra data with the received bundle. Show a Toast with the extra data to validate that you correctly received it. The following code contains some pointer on how to solve that. Create a user in your application and start the training. An Intent is a messaging object you can use to request an action from another app component.

Although intents facilitate communication between components in several ways, there are three fundamental use cases:. An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startActivity. The Intent describes the activity to start and carries any necessary data. If you want to receive a result from the activity when it finishes, call startActivityForResult.

Your activity receives the result as a separate Intent object in your activity's onActivityResult callback. For more information, see the Activities guide. A Service is a component that performs operations in the background without a user interface. With Android 5. For versions earlier than Android 5. You can start a service to perform a one-time operation such as downloading a file by passing an Intent to startService. The Intent describes the service to start and carries any necessary data.

If the service is designed with a client-server interface, you can bind to the service from another component by passing an Intent to bindService. For more information, see the Services guide.

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 or sendOrderedBroadcast.

The rest of this page explains how intents work and how to use them. Figure 1 shows how an intent is used when starting an activity. When the Intent object names a specific activity component explicitly, the system immediately starts that component. Figure 1. How an implicit intent is delivered through the system to start another activity: [1] Activity A creates an Intent with an action description and passes it to startActivity.

When a match is found, [3] the system starts the matching activity Activity B by invoking its onCreate method and passing it the Intent. When you use 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.

An intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive. For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.

Caution: To ensure that your app is secure, always use an explicit intent when starting a Service and do not declare intent filters for your services. Using an implicit intent to start a service is a security hazard because you can't be certain what service will respond to the intent, and the user can't see which service starts.

Beginning with Android 5. An Intent object carries information that the Android system uses to determine which component to start such as the exact component name or component category that should receive the intent , plus information that the recipient component uses in order to properly perform the action such as the action to take and the data to act upon.

The primary information contained in an Intent is the following:. This is optional, but it's the critical piece of information that makes an intent explicit , meaning that the intent should be delivered only to the app component defined by the component name. Without a component name, the intent is implicit and the system decides which component should receive the intent based on the other intent information such as the action, data, and category—described below.

If you need to start a specific component in your app, you should specify the component name. Note: When starting a Service , always specify the component name. Otherwise, you cannot be certain what service will respond to the intent, and the user cannot see which service starts.

This field of the Intent is a ComponentName object, which you can specify using a fully qualified class name of the target component, including the package name of the app, for example, com.

You can set the component name with setComponent , setClass , setClassName , or with the Intent constructor. Action A string that specifies the generic action to perform such as view or pick. In the case of a broadcast intent, this is the action that took place and is being reported. The action largely determines how the rest of the intent is structured—particularly the information that is contained in the data and extras. You can specify your own actions for use by intents within your app or for use by other apps to invoke components in your app , but you usually specify action constants defined by the Intent class or other framework classes.

Here are some common actions for starting an activity:. See the Intent class reference for more constants that define generic actions. Other actions are defined elsewhere in the Android framework, such as in Settings for actions that open specific screens in the system's Settings app. You can specify the action for an intent with setAction or with an Intent constructor. If you define your own actions, be sure to include your app's package name as a prefix, as shown in the following example:.

For example, 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. Specifying the MIME type of your data helps the Android system find the best component to receive your intent. To set only the data URI, call setData. If necessary, you can set both explicitly with setDataAndType. Category A string containing additional information about the kind of component that should handle the intent. Any number of category descriptions can be placed in an intent, but most intents do not require a category.

See the Intent class description for the full list of categories. You can specify a category with addCategory. These properties listed above component name, action, data, and category represent the defining characteristics of an intent.

By reading these properties, the Android system is able to resolve which app component it should start. However, an intent can carry additional information that does not affect how it is resolved to an app component.

An intent can also supply the following information:. You can add extra data with various putExtra methods, each accepting two parameters: the key name and the value. You can also create a Bundle object with all the extra data, then insert the Bundle in the Intent with putExtras. If you need to declare your own extra keys for intents that your app receives , be sure to include your app's package name as a prefix, as shown in the following example:. Caution : Do not use Parcelable or Serializable data when sending an intent that you expect another app to receive.

If an app attempts to access data in a Bundle object but does not have access to the parceled or serialized class, the system raises a RuntimeException.

For more information, see the setFlags method. 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. For example, if you built a service in your app, named DownloadService , designed to download a file from the web, you can start it with the following code:. As such, this intent explicitly starts the DownloadService class in the app. For more information about building and starting a service, see the Services guide. An implicit intent specifies an action that can invoke any app on the device able to perform the action.

Using an implicit intent is useful when your app cannot perform the action, but other apps probably can and you'd like the user to pick which app to use. When you call startActivity with that intent, the user can pick an app through which to share the content. If there's only one app that can handle it, that app opens immediately and is given the intent.

If no other apps can handle it, your app can catch the ActivityNotFoundException that occurs. If multiple activities accept the intent, the system displays a dialog such as the one shown in Figure 2, so the user can pick which app to use. More information about launching other apps is also provided in the guide about sending the user to another app. 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.

The ability to select a default is helpful when performing an action for which the user probably wants to use the same app every time, such as when opening a web page users often prefer just one web browser.

However, 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 the user cannot select a default app for the action.

To show the chooser, create an Intent using createChooser and pass it to startActivity , as shown in the following example. This example displays a dialog with a list of apps that respond to the intent passed to the createChooser method and uses the supplied text as the dialog title. Your app might launch intents to navigate between components inside of your app, or to perform an action on behalf of another app.

To improve platform security, Android 12 API level 31 and higher provide a debugging feature that warns you if your app performs an unsafe launch of an intent. For example, your app might perform an unsafe launch of a nested intent , which is an intent that is passed as an extra in another intent.

If your app performs both of the following actions, the system detects an unsafe intent launch, and a StrictMode violation occurs:. For more details on how to identify this situation and make changes to your app, read the blog post about Android Nesting Intents on Medium. To check for unsafe intent launches in your app, call detectUnsafeIntentLaunch when you configure your VmPolicy , as shown in the following code snippet.

If your app detects a StrictMode violation, you might want to stop app execution to protect potentially sensitive information. To minimize the chance of an unsafe intent launch, and a StrictMode violation, follow these best practices.

Copy only the essential extras within intents, and perform any necessary sanitation and validation. Your app might copy the extras from one intent to another intent that is used to launch a new component.

This occurs when your app calls putExtras Intent or putExtras Bundle. If your app performs one of these operations, copy only the extras that the receiving component expects.

If the other intent that receives the copy launches a component that isn't exported , sanitize and validate the extras before copying them to the intent that launches the component. Don't export your app's components unnecessarily. For example, if you intend to launch an app component using an internal nested intent, set that component's android:exported attribute to false. Use a PendingIntent instead of a nested intent. That way, when another app unparcels the PendingIntent of its containing Intent , the other app can launch the PendingIntent using the identity of your app.

This configuration allows the other app to safely launch any component, including a non-exported component, in your app. The diagram in figure 2 shows how the system passes control from your client app to another service app, and back to your app:.

Figure 2. Diagram of inter-app communication when using a nested pending intent. Each intent filter specifies the type of intents it accepts based on the intent's action, data, and category. The system delivers an implicit intent to your app component only if the intent can pass through one of your intent filters. Note: An explicit intent is always delivered to its target, regardless of any intent filters the component declares.

An app component should declare separate filters for each unique job it can do. For example, one activity in an image gallery app may have two filters: one filter to view an image, and another filter to edit an image.

When the activity starts, it inspects the Intent and decides how to behave based on the information in the Intent such as to show the editor controls or not. This attribute indicates whether the app component is accessible to other apps. Otherwise, it's safer to set this attribute to false. Warning: If an activity, service, or broadcast receiver in your app uses intent filters and doesn't explicitly set the value for android:exported , your app can't be installed on a device that runs Android 12 or higher.

If you do not declare this category in your intent filter, no implicit intents will resolve to your activity. If you do, you need to be certain that the component can handle any and all combinations of those filter elements.

When you want to handle multiple kinds of intents, but only in specific combinations of action, data, and category type, then you need to create multiple intent filters.

Cloud Computing. Data Science. Angular 7. Machine Learning. Data Structures. Operating System. Computer Network. Compiler Design. Computer Organization.

Discrete Mathematics. Ethical Hacking. Computer Graphics. Software Engineering. Web Technology. Cyber Security. C Programming. Control System. Data Mining.



0コメント

  • 1000 / 1000