关于显示启动不用多做介绍比较简单,今天主要整理下隐式启动注意的地方,方便以后自己查阅。
隐式启动不需要指定包名和类名,隐式启动的调用需要Intent能够匹配目标组件的IntentFilter中的信息。
1.首先在Application中配置
隐式启动的信息,主要有action,category和data,
如下图所示:
<activity android:name=".yinshi.IntentTestActivity">
<intent-filter>
<action android:name="com.action.1"/>
<action android:name="com.action.2"/>
<category android:name="com.cate.1"/>
<category android:name="com.cate.2"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" android:scheme="file" />
</intent-filter>
<intent-filter>
........
</intent-filter>
</activity>
可以看到,在一组intent-filter中有action,category和data三种类型的标签,我们必须同时匹配action,category和data的信息才能跳转,action,category和data可以有多个,一个activity可以有多个intent-filter,我们只需要匹配一组intent-filter即可成功跳转。
2.action,category和data匹配规则
action可以设置多组,但是只要有一组匹配上即可(至少一组),如上面所示我们可以设置Intent的action为com.action.1或com.action.2都可以匹配成功。
如果只写一条可以直接在Intent的构造函数写:
Intent intent1=new Intent("com.action.1");
多条也可以继续添加
intent1.setAction("com.action.2");
category不太一样,我们可以不为intent设置category,但是intent-filter需要设置”android.intent.category.DEFAULT”这一条category,因为在系统调用startActivity或者startActivityForResult的时候会默认为Intent指定这一条category。
<category android:name="android.intent.category.DEFAULT"/>
为Intent添加category:
intent1.addCategory("com.cate.1");
data的匹配规则和action类似,如果规则中定义了data,那么Intent中也必须进行设置。
data由两部分组成mimeType和URI,mimeType指媒体类型,比如:image/png、music/mp3,你也可以随便写如 hehe/abc,但是非常不推荐,URI的结构如下:
Scheme: URI的模式,比如file、http等
Host:URI的主机名,比如www.baidu.com
Port:URI的端口号,比如80,一般在Host之后
Path:表示路径信息
用于指定可以处理的数据类型,允许使用通配符的方式进行指定。只有标签中指定的内容和 Intent 中携带的 Data 完全一致时,当前活动才能够响应该 Intent。不过一般在标签中都不会指定过多的内容,常见的是mimeType和scheme。
如我们在过滤信息中写如下信息
<data android:scheme="http" />
我们可以在Intent中可以这样,即可匹配成功
intent1.setData(Uri.parse("http://abc"));
我们在过滤信息中这样写
<data android:mimeType="text/pain" />
我们可以在Intent中可以这样,也可匹配成功
intent1.setType("text/pain");
但是当我们在过滤信息中这样写
<data android:mimeType="text/pain" android:scheme="http" />
如果在Intent中这样,就会报错
intent1.setData(Uri.parse("http://abc"));
intent1.setType("text/pain");
我们必须调用setDataAndType方法将两个方法合起来才可以
intent1.setDataAndType(Uri.parse("http://abc"),"text/pain");
这是因为setData和setType会清除掉彼此的值,看源码就知道如下:(setType类似)
public Intent setData(Uri data) {
mData = data;
mType = null;
return this;
}
会把彼此置为null,这也是不少人掉坑的地方。
完整的例子如下
过滤信息:
<activity android:name=".yinshi.IntentTestActivity">
<intent-filter>
<action android:name="com.action.1"/>
<action android:name="com.action.2"/>
<category android:name="com.cate.1"/>
<category android:name="com.cate.2"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/pain" android:scheme="http" />
</intent-filter>
</activity>
Intent 信息如下:
Intent intent1=new Intent("com.action.1");
intent1.setAction("com.action.2");
intent1.addCategory("com.cate.1"); intent1.setDataAndType(Uri.parse("http://abc"),"text/pain");
startActivity(intent1);