隐式Intent用法

来源:互联网 发布:nginx 1.8 域名配置 编辑:程序博客网 时间:2024/06/08 15:30

1.隐式Intent的用法之一
通过在标签下配置的内容,可以指定当前活动能够响应的 action和 category,打开 AndroidManifest.xml,添加如下代码:

<activity android:name=".SecondActivity" ><intent-filter><action android:name="com.example.activitytest.ACTION_START" /><category android:name="android.intent.category.DEFAULT" /></intent-filter></activity>

修改 FirstActivity 中按钮的点击事件,代码如下所示:

button1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent("com.example.activitytest.ACTION_START");startActivity(intent);}});

可以看到,我们使用了 Intent 的另一个构造函数,直接将 action 的字符串传了进去,表明我们想要启动能够响应 com.example.activitytest.ACTION_START 这个 action 的活动。
每个 Intent 中只能指定一个 action,但却能指定多个 category。目前我们的 Intent 中只有一个默认的 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);}});

2.隐式Intent的用法之二(启动一个网页)

Intent intent2=new Intent(Intent.ACTION_VIEW);              intent2.setData(Uri.parse("http://www.baidu.com"));startActivity(intent2);

这里我们首先指定了 Intent 的 action 是 Intent.ACTION_VIEW, 这是一个 Android 系统内置的动作,其常量值android.intent.action.VIEW。然后通过 Uri.parse()方法,将一个网址字符串解析成一个 Uri 对象,再调用 Intent 的 setData()方法将这个 Uri 对象传递进去。

0 0
原创粉丝点击