Android中提供intent机制提供应用间的通信。Intent负责对应用中一次操作的动作、动作涉及数据、附加数据进行描述,Android则根据此Intent的描述,负责找到对应的组件,将 Intent传递给调用的组件,并完成组件的调用。Intent不仅可用于应用程序之间,也可用于应用程序内部的Activity/Service之间的交互。因此,可以将Intent理解为不同组件之间通信的“媒介”专门提供组件互相调用的相关信息。
intent可以启动一个Activity,Service,也可以发送一个BroadCast。
启动一个Activity,可以使用 startActivity() 和 startActivityForResult()方法。
启动一个Service,可以使用 startService() 和 bindService() 方法。
发送一个广播,可以使用 sendBroadcast() , sendOrderBroadcast() 和 sendStickyBroadcast() 方法,sendStickyBroadcast()方法已经被弃用了。
Intent有以下几个属性:
动作(Action),数据(Data),分类(Category),类型(Type),组件(Component),扩展(Extra),标志(Flag)。
Action: String类型,用于指定某一种特定的动作,可以自定义,一般命名方式为 包名作为前缀+特定的大写字符串。
Action是指Intent要完成的动作,是一个字符串常量,可以调用系统服务。SDK中定义了一些标准的Action常量如下表所示。
Constant |
Target component |
Action |
ACTION_CALL |
activity |
Initiate a phone call. |
ACTION_EDIT |
activity |
Display data for the user to edit. |
ACTION_MAIN |
activity |
Start up as the initial activity of a task, with no data input and no returned output. |
ACTION_SYNC |
activity |
Synchronize data on a server with data on the mobile device. |
ACTION_VIEW | activity | Display user data |
ACTION_BATTERY_LOW |
broadcast receiver |
A warning that the battery is low. |
ACTION_HEADSET_PLUG |
broadcast receiver |
A headset has been plugged into the device, or unplugged from it. |
ACTION_SCREEN_ON |
broadcast receiver |
The screen has been turned on. |
ACTION_TIMEZONE_CHANGED |
broadcast receiver |
The setting for the time zone has changed |
Category: String类型,用于指定目标组件需要满足的额外条件,也可自定义,命名方式同Action。
下表是SDK文档中关于Category的信息。
Constant |
Meaning |
CATEGORY_BROWSABLE |
The target activity can be safely invoked by the browser to display data referenced by a link — for example, an image or an e-mail message. |
CATEGORY_GADGET |
The activity can be embedded inside of another activity that hosts gadgets. |
CATEGORY_HOME |
The activity displays the home screen, the first screen the user sees when the device is turned on or when the HOME key is pressed. |
CATEGORY_LAUNCHER |
The activity can be the initial activity of a task and is listed in the top-level application launcher. |
CATEGORY_PREFERENCE |
The target activity is a preference panel. |
每个组件可以设置多个Action和Category属性,对于每个intent,只要组件满足其所有的Action和Category属性,便会响应intent。
Data: Uri类型, 用于指定操作数据的Uri。可以是本地的一个文件,也可以是一个http链接。
Type: String类型,用于指定Data的MIME属性,系统将会根据数据类型选择合适的应用执行intent。
Component: ComponentName类型,需要包名+类名进行唯一识别。相比于action和view,更加直接 。
Extra: 用于记录intent携带的额外数据,数据类型有 基本数据类型,String, Serializable类型,Parcelable类型,Bundle类型,以及以上类型的数组。
Flag: int类型,用于通知Android系统如何启动目标Activity,或启动Activity后,应该采取怎样的后续操作
- FLAG_ACTIVITY_NEW_TASK
使用场合:当在一个Activity的Context之外调用startActivity()去启动一个新的ActivityA1时,需要设置该标志。
额外说明:当调用者想要从A1中请求一个结果,则不能设置该标志。
- FLAG_ACTIVITY_NO_HISTORY
使用场合:当需要用户离开Activity时,该Activity便被系统销毁。