1.Component属性
代表启动的目标组件
public Intent(Context packageContext, Class<?> cls) {
throw new RuntimeException("Stub!");
}
Intent intent = new Intent(ComponentAttr.this,SecondActivity.class);
一般显式跳转都是利用这个
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
2.Action,Category属性和intent-filter配置
action代表的是一个抽象的动作,category提供一些附加信息
intent-filter是位于manifest文件中的,其中可以包含多个Action和Category
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="hello"/>
<action android:name="hello2"/>
<category android:name="world"/>
<category android:name="world1"/>
</intent-filter>
</activity>
但是使用intent跳转的时候只能包含一个action,至少一个category
Action通过intent.setAction("hello");来实现
Category通过intent.addCategory("world");来实现
只要action和category同时符合intent-filter就能跳转(当然这是在没有data属性的前提下),同时符合的组件可能不止一个,如果多个符合,会让你选择。
通过startActivity或startActivityForResult()会自动加上android.intent.category.DEFAULT
3.Data、Type和intent-filter配置
在目标<data/>标签中包含了以下几种子元素,他们定义了url的匹配规则:
android:scheme 匹配url中的前缀,除了“http”、“https”、“tel”...之外,我们可以定义自己的前缀
android:host 匹配url中的主机名部分,如“google.com”,如果定义为“*”则表示任意主机名
android:port 匹配url中的端口
android:path 匹配url中的路径
Type就是一种MIME类型,暂时还不是特别懂
在intent-filter中可以声明Data和Type
<activity android:name=".TargetActivity">
<intent-filter>
<action android:name="com.scott.intent.action.TARGET"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="scott" android:host="com.scott.intent.data" android:port="7788" android:path="/target"/>
</intent-filter>
</activity>
通过setData(Uri uri)就可以实现,但setData()中接受参数Uri,所以需要转换一下
Uri uri = Uri.parse("http://www.baidu.com/2.asp");
intent.setData(uri);
只要intent-filter中所有Data中的数据都符合,就可以跳转,
<intent-filter>
<data
...
android:host="shandong.mm"
android:scheme="ottp" />
</intent-filter>
<intent-filter>
<data
...
android:host="shandong.mm"
android:port="8080"
android:scheme="ottp" />
</intent-filter>
以上两种在
Uri uri= Uri.parse(
"ottp://shandong.mm:8080/pathparent/pathchild"
);
的情况下都可以跳转,当然上面省略了action和category
4.Extra属性
Extra属性主要是为了携带需要交换的数据
intent的putExtras(Bundle extras) 传入一个Bundle类型
intent的putExtra(..)这个方法取单个key-value值 比较多样,可以查看intent的官方文档
//第一种方式直接使用intent.putExtra封装,这种方式本质也是操作Bundle)
// intent.putExtra("id", id);
// intent.putExtra("name", name);
// intent.putExtra("salary", salary);
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
/*
* 第二种方式使用Bundle封装数据
*/
Bundle bundle = new Bundle();
bundle.putInt("id", id);
bundle.putString("name", name);
bundle.putFloat("salary",salary);
intent.putExtras(bundle);