当前位置:操作系统 > 安卓/Android >>

Intent与<intent-filter>

耐心看完,你就能搞明白怎么Intent一个系统程序了。
@Intent结构
private String mAction;
private Uri mData;
private String mType;
private String mPackage;
private ComponentName mComponent;
private int mFlags;
private HashSet<String> mCategories;
private Bundle mExtras;
private Rect mSourceBounds;
@<intent-filter>元素与属性
intent-filter中有三个元素:action、category、data,这三个元素都是可以有多个的。
action和category元素只有android:name一条属性,而data则有scheme,host,prot,path,pathPrefix,pathPattem,mimeType七条属性。
@Intent中变量与intent-filter中元素对应关系
action与Intent中的mAction元素相对应;
category与Intent中的mCategories相对应;
data中的mimeType与Intent中的mType相对应;
data中的其余六条则与Intent中的mData相对应。
由此可见,Intent中与intent-filter相关的只有四个参数,mAction、mData、mType、mCategories,而这四个参数对应的操作如下:
Intent.setAction(String action);
Intent.addCategory(String category);
Intent.removeCategory(String category);
Intent.setType(String type);
Intent.setData(Uri data);
Intent.setDataAndType(Uri data, String type);
需要注意的是:setType会清空mData,而setData也会清空mType,如果要同时设置mType和mData则必须用setDataAndType。
这里的Uri=scheme://host:port/path。
如果没定义path、port、host则Uri=scheme://。
这里重点说一下path、pathPrefix和pathPattem:
path 用来匹配完整路径
pathPrefix 用来匹配路径的开头部分
pathPattem 用表达式来配置完整路径,"*"表示0个或多个其前面的字符,"."表示1个任意字符,".*"则可以表示0个或多个任意字符。
@Intent与intent-filter匹配规则
a、Intent定义的Action必须包含在<intent-filter>的Action列表总,若隐式Intent没有定义Action则系统会报错。
b、Intent若定义了Category(可多个),则所有Category必须包含在<intent-filter>的Category列表里,若Intent未定义Category则<intent-filter>中是否定义了Category都不受影响,<intent-filter>中必须包含<category android:name="android.intent.category.DEFAULT">才能通过startActivity启动,Service和Broadcast Receiver则不需要。
c、Intent若未定义Type,则其仅匹配同样没有定义Type的intent-filter,若定义了则必须在intent-filter中有相匹配的项。
d、Intent若未定义Uri,则其仅匹配同样没有定义uri的intent-filter,若定义了则必须在intent-filter中有相匹配的项。
@显式与隐式Intent
显式Intent通常用于程序内部间的组件通信,已经明确的定义了目标组件的信息,所以不需要系统决策用哪个目标组件,如:
Intent intent = new Intent(Context packageContext, Class<?> clas);
startActivity(intent);
隐式Intent不指明目标组件的class,只定义希望的Action、Category和Data,由系统决定使用哪个目标组件。这也是Android系统的一大亮点。
第三种,可以用PackageManager获取系统中安装的所有包,然后打开:
PackageManager packageManager = getBaseContext().getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveInfoList = packageManager.queryIntentActivities(intent, 0);//根据intent来搜索
Intent intent = new Intent();
intent.setComponent(new ComponentName(String pkg, String cls));
startActivity(intent);
@前面忘了说了,还要下载一份android源代码,然后在packages/apps目录下找到你要调用的程序,查看他的Manifest.xml。
 
补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,