您的位置:首页 > 移动开发

Android ApiDemos详解之App_Activity_Intents(8)

2012-01-06 20:48 337 查看
Android ApiDemos详解之App_Activity_Intents
该示例很简单,功能只有一个,就是搜索出所有的音频文件,废话少说,直入主题:

先看布局,进入该示例后只有一个TextView和一个Button屹立着:



点击”Get Music”按钮后,会搜索当前设备内的所有音频文件,并以列表方式显示出来,单击歌曲可以进行收听,底栏的”OK”和”Cancel”按钮功能如其说明:



布局代码我们就不看了,很简单只有一个按钮,主要看一下该按钮监听器的实现,代码如下:

private OnClickListener mGetMusicListener = new OnClickListener(){
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivity(Intent.createChooser(intent,"Select music"));
}
};


Intent大家都很熟悉,作用是用来激活应用程序中活动,广播,服务,Intent本身是一个包含被执行操作抽象描述的数据结构,Intent的目的是为了找到一个能够正确回应Intent对象描述的组件。在本例中,intent对象采用了

public Intent(String action)


这一构造函数,



Intent.ACTION_GET_CONTENT
这一String变量描述了能正确回应该Intent描述的组件所应具备的一个action,这一action描述应当出现在目标组件的action描述中:

<intent-filter android:label="@string/xxxx">
<action android:name=" android.intent.action.GET_CONTENT " />
</intent-filter>


说到这里顺便解释下在AndroidManifest.xml文件中<intent-filter></intent-filter>中的<action/>和<category>的区别,举个例子,假使有两个Activity分别是A和B,想通过Intent从A跳转到B,其中在B的<intent-filter>中有

<action android:name=”actionB1”>
<action android:name=”actionB2”>
<action android:name=”actionB3”>
<category android:name=”category B1”>
<category android:name=”category B2”>


那么需要满足什么样的条件才能实现正确的跳转呢,对于aciton来说,只要Intent所描述的action满足在B所列出的aciton中(也即就是actionB1, actionB2, actionB3)的任意一个,那么B就可以认为满足跳转条件,或者能通过的条件是Intent没有设置任何action而只要B拥有至少一个action也可以满足条件,而不满足条件的当然就是Intent设置了action但是在B的action描述中却找不到。

再说说category,这个就比较严格了,官方解释是这样的“For an intent to pass thecategory test, every category in the Intent object must match a category in thefilter. The filter
can list additional categories, but it cannot omit any thatare in the intent. “,映射到我举得这个例子中的意思就是,Intent所描述的所有category必需都要在B的category条件中,且B中的category描述可以多,但是必需囊括Intent中所有的描述,形象点就是category(Intent)<=category(B)。

回到正题,在设置完该Intent的action之后,intent.setType("audio/*");通过查看setType()方法的官方注释可以知道:

“Set an explicit MIME data type.This is used to create intents that only specify a type and not data, forexample to indicate the type of data to return. This method automatically clears
any data that was previously set by setData().”意思映射到上面那个例子就是该方法用以约束intent所要匹配的组件可以处理”audio”类型的数据,并且会自动屏蔽掉setData()所设置的效果。本例中指明了目标组件要处理音频文件。
最后一行代码:

startActivity(Intent.createChooser(intent,"Select music"));


目的很简单,就是通过该Intent去找到一个能满足Intent对象所描述类型的组件,并且设置标题为“Select music“。结果就是该示例在设备上找到了对应的用于播放音频文件的一个Activity组件。
大家可以自己写一个例子,尝试一下给Intent对象设置其他的Type,如”image/*”,看看有什么效果。本期结束
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: