Android笔记(五)利用Intent启动活动

Intent是意图的意思,分为显式 Intent 和隐式 Intent。

以下我们试图在FirstActivity中通过点击button来启动SecondActivity
1.显式Intent
在应用中建立两个类,FirstActivity和SecondActivity。分别为它们建立layout布局文件first_layout,second_layout,并在AndroidManifest.xml中注冊。
Intent的使用方法: Intent(Context packageContext, Class cls)。
这个构造函数接收两个參数。第一个參数 Context 要求提供一个启动活动的上下文。第二个參数 Class 则是指定想要启动的目标活动。 通过这个构造函数就能够构建出 Intent 的“意图”。


将FirstActivity中button1的响应事件改动为
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
光有意图还不够。Activity 类中提供了一个 startActivity()方法,这种方法是专门用于启动活动的,它接收一个 Intent參数,这里我们将构建好的 Intent传入 startActivity()方法就能够启动目标活动了。
2.隐式意图
隐式Intet并不明白指出我们想要启动哪一个活动。而是指定了一系列更为抽象的 action 和 category 等信息,然后交由系统去分析这个 Intent,
并帮我们找出合适的活动去启动。


AndroidManifest.xml中在SecondActivity里加入

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

然后改动 FirstActivity 中button的点击事件
Intent intent = new Intent(“com.example.activitytest.ACTION_START”);
startActivity(intent);
由于动作相匹配,而类别是默认的,所以也能启动SecondActivity
每一个 Intent 中仅仅能指定一个 action,但却能指定多个 category。眼下我们的 Intent 中仅仅有一个默认的 category。那么如今再来添加一个吧。
Intent intent = new Intent(“com.example.activitytest.ACTION_START”);
intent.addCategory(“com.example.activitytest.MY_CATEGORY”);
startActivity(intent);
那么,我们在AndroidManifest.xml中注冊的活动也要改动对应的类别才干响应这个Intent

 <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>

再次又一次启动程序,就ok了。
3.隐式Intent的还有一个功能:显示网页
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(“http://www.baidu.com“));
startActivity(intent);
uri是统一资源标识符的缩写。先将百度的网址转化成统一资源标识符,然后在传入intent,ACTION_VIEW会依据传入的数据类型打开对应的活动,本例中打开的是网页,也能够打开拨号程序。地图定位等。


< intent-filter >标签中有一个< data >标签,用于指定当前活动响应什么类型的数据,< data >标签中主要能够配置以下内容
1. android:scheme
用于指定数据的协议部分。如 http部分 。
2. android:host
用于指定数据的主机名部分。如 www.baidu.com 部分。
3. android:port
用于指定数据的port部分。一般紧随在主机名之后。
4. android:path
用于指定主机名和port之后的部分,如一段网址中跟在域名之后的内容。
5. android:mimeType
用于指定能够处理的数据类型,同意使用通配符的方式进行指定。
仅仅有< data >标签中指定的内容和 Intent 中携带的 Data 全然一致时。当前活动才干够响应该 Intent。

只是一般在< data >标签中都不会指定过多的内容。如上面浏览器演示样例中。事实上仅仅须要指定 android:scheme 为 http,就能够响应全部的 http 协议的 Intent 了。

以下这个就是能够打开网页的活动

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>

调用系统拨号界面

Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);

Intent 的 action 是 Intent.ACTION_DIAL,这又是一个 Android 系统的内置动作。然后在 data 部分指定了协议是 tel。号码是 10086。效果如图:

这里写图片描写叙述

posted @ 2017-08-10 11:19  zsychanpin  阅读(223)  评论(0编辑  收藏  举报