---
title: "Intent和Intent Filters"
author: "jguangyou"
date: "2014-04-24T11:15:55Z"
tags: []
categories: ["移动开发"]
slug: "intent-intent-filters"
draft: false
lastmod: "2014-04-24T13:44:17Z"
id: 2054004
url: "https://deep-fish.iteye.com/blog/2054004"
---

Intent主要包含Componet name、Action、category、data、type、Extras以及flag。

- **Componet name**

       启动一个组件最直接的方式就是通过Componet name，也就是组件名称，它是一个[ComponentName](http://developer.android.com/reference/android/content/ComponentName.html)对象，指定组件可以通过一下几种方式：

[setComponent(ComponentName)](http://developer.android.com/reference/android/content/Intent.html#setComponent%28android.content.ComponentName%29)

 

- `setClass(Context, Class)`
- `setClassName(Context, String)`
- `setClassName(String, String)`

 

 

其实下面的三种方式，最后调用的还是      [setComponent(ComponentName)](http://developer.android.com/reference/android/content/Intent.html#setComponent%28android.content.ComponentName%29)方法 。例如启动一个activity：

 

```
intent.setComponent(new ComponentName("com.hs","ActivityA"));
startActivity(intent);
```

- **Action**

Action是一个普通的字符串，他代表Intent要完成的一个抽象动作，这个动作具体有哪个组件完成，action字符串本身并不关心。例如Android提供的标准Action：Intent.ACTION\_VIEW,它只代表一个抽象的查看动作，但是具体查看什么，启动哪个activity来查看，它是并不知道的，还必须需要其他附加信息来决定，例如category等。但是有一点，那就是只要activity的&lt;Intent-filter&gt;中包含这个action，这个activity就可能启动。

给intent设置action的方法为 `setAction()` 。

需要说明的是，在Android系统本身定义了许多标准的action，具体参看[http://developer.android.com/reference/android/content/Intent.html](http://developer.android.com/reference/android/content/Intent.html)

 

- **category**

category也是一个字符串，他为action增加额外的附加信息，例如 `CATEGORY_LAUNCHER，证明这是一个Launcher。`

系统也有许多标准定义的category，请参考[http://developer.android.com/reference/android/content/Intent.html](http://developer.android.com/reference/android/content/Intent.html)

- **data**

data是指提供的操作数据，例如电话联系人数据等。他的访问方式是通过URI对象来访问。例如：***content://contacts/people/1***

- ***type***

type指的是data数据的数据类型或者MIME类型。一般情况下可以通过数据来推断出类型。一般情况下，data和type只要设置一个就可以了，设置data通过[setData()](http://developer.android.com/reference/android/content/Intent.html#setData%28android.net.Uri%29).  设置MIME 类型，使用[setType()](http://developer.android.com/reference/android/content/Intent.html#setType%28java.lang.String%29)， 如果要两个都设置，你可以使用 `setDataAndType()`.

- **Extras**

这是一个额外的信息。这可以用于为组件提供扩展的信息。例如，如果我们有一个行动，发送电子邮件，我们还可以包括额外的数据块来供给主体，主体，等。使用方法[putExtra(String, Bundle)](http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20android.os.Bundle%29).

- **flag**

**[http://developer.android.com/reference/android/content/Intent.html#setFlags(int](http://developer.android.com/reference/android/content/Intent.html#setFlags%28int))**

 

更多内容查看[http://developer.android.com/guide/components/intents-filters.html](http://developer.android.com/guide/components/intents-filters.html)