📜  Android中隐式意图和显式意图的区别

📅  最后修改于: 2021-09-13 02:03:07             🧑  作者: Mango

意图是一个消息对象,它告诉要执行的操作类型。意图最重要的用途是启动活动。 Intent 是一个被动数据结构,包含对要执行的操作的抽象描述。

意图主体:

意图中有两件重要的事情

  • action:要执行的一般动作,如ACTION_VIEW、ACTION_EDIT、ACTION_MAIN等。
  • data:要操作的数据,比如联系人数据库中的一个人记录,表示为一个Uri

Android Intent 的类型

android中有两种类型的意图:

  1. 隐式和
  2. 明确的。

1. 隐含意图

隐式意图不指定组件。在这种情况下,意图提供有关由要调用的系统提供的可用组件的信息。例如,您可以编写以下代码来查看网页。

例子:

在下面的图片中,没有指定组件,而是执行一个动作,即要打开一个网页。当您键入所需网页的名称并单击“单击”按钮时。您的网页已打开。

隐含意图

2. 显式意图

显式意图指定组件。在这种情况下,意图提供要调用的外部类。

例子:

在下面的示例中,有两个活动(FirstActivity、SecondActivity)。当您单击FirstActivity 中的“转到其他活动”按钮时,您将移至第二个活动。当您单击SecondActivity 中的“GO TO HOME ACTIVITY”按钮时,您将移至第一个活动。这是通过显式意图完成的。

现在让我们找出这两者之间的主要区别。

差异表

Explicit Intent

Implicit Intent

As already mentioned above explicit intents are those in which the user has a clear vision and knows exactly which activity can handle the requests.

Example: When you have a Listview screen on tap of each item you will go to detail activity  

Intent = Intent(applicationContext,DetailActivity::class.java)

startActivity(intent) 

Implicit intents do not name a specific component like 

explicit intent, instead declare general action to perform,

which allows a component from another app to handle.

Example: When you tap the share button in any app you can see the Gmail, Bluetooth, and other sharing app options. Here user sends a request is the implicit intent request which can be handle by these Gmail, Bluetooth-like app.

Explicit intent can do the specific application action which is set by the code like changing activity, downloading the file in the background, etc.

It specifies the only action to be performed and 

does not directly specify Android Components.

In explicit intent, you can pass data to other activity by using the putExtra method and retrieve by using getIntent().

Example:

val intent = Intent(this, SecondActivity:: class.java).apply{

putExtra(“key”,”New Value”)

}

startActivity(intent)

Second Screen:

val secondIntent = intent.getStringExtra(“key”)

Here we just mention the action in the intent and OS 

decides which applications are suitable to handle the task, 

action across two different applications.

Explicit intents are used for communication inside the application. Like changing activities inside the application. They are used for communication across two different applications.
In explicit intent, the action target is delivered even the filter is not consulted. When you make an implicit call with the intent. OS look at the action and then it matches with all the filters intent-filters of all the registered activities of all application using PackageManager and then populates the result as a list, this process is called as intent Resolution. 
想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!