首页 > 学院 > 开发设计 > 正文

隐式Intent

2019-11-09 14:57:30
字体:
来源:转载
供稿:网友

本人小白,大学期间,打算开始自学Android,准备用博客写下所学所得,希望有所收获,望大家互相帮助

相比于显式 Intent,隐式Intent 则含蓄了许多,它并不明确指出我们想要启动哪一个活动,而是指定了一系列更为抽象的action 和 category等信息,然后交由系统去分析这个 Intent,并帮我们找出合适的活动去启动。

在AndroidManifest.xml 中可以指定当前活动能够响应的action和 category 

打开 AndroidManifest.xml,添加如下代码:<activity android:name=".SecondActivity" ><intent-filter><action android:name="com.example.activitytest.ACTION_START" /> //在<action>标签中我们指明了当前活

//动可以响应com.example.activitytest.ACTION_

//START这个 action <category android:name="android.intent.category.DEFAULT" />//<category>标签则包含了一些附加信息,

//更精确地指明了当前的活动//能够响应的 Intent 中还可能带有的category </intent-filter></activity> 只有<action>和<category>中的内容同时能够匹配上Intent 中指定的 action 和 category时,这个活动才能响应该 Intent。 

修改 FirstActivity 中按钮的点击事件,代码如下所示:button1.setOnClickListener(new OnClickListener() {public void onClick(View v) {Intent intent = new Intent("com.example.activitytest.ACTION_START");startActivity(intent);}}); 

我们使用了 Intent的另一个构造函数,直接将 action的字符串传了进去,表明我们想要启动能够响应com.example.activitytest.ACTION_START这个 action 的活动。 

java代码中没指定category  是因为android.intent.category.DEFAULT是一种默认的 category,在调用startActivity()方法的时候会自动将这个category 添加到 Intent 中。 每个 Intent 中只能指定一个action,但却能指定多个 category。 修改 FirstActivity 中按钮的点击事件,代码如下所示:button1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent("com.example.activitytest.ACTION_START");intent.addCategory("com.example.activitytest.MY_CATEGORY");startActivity(intent);}}); 可以调用 Intent 中的addCategory()方法来添加一个category,这里我们指定了一个自定义的category,值为 com.example.activitytest.MY_CATEGORY。记得要在SecondActivity 的<intent-filter>标签中并没有声明可以响应这个category 在<intent-filter>中再添加一个category 的声明,如下所示:<activity android:name=".SecondActivity" ><intent-filter><action android:name="com.example.activitytest.ACTION_START" /><category android:name="android.intent.category.DEFAULT" /><category android:name="com.example.activitytest.MY_CATEGORY"/></intent-filter></activity>


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表