Android Intent

1.显式Intent
Intent有多个构造函数的重载,其中一个是:

Intent(Context packageContext,Class<?> cls).

这个构造函数接收两个参数,第一个参数Context要求提供一个启动活动的上下文,第二个参数Class则是指定想要启动的目标活动,通过这个构造函数就可以构建出Intent的意图.
Intent的使用:

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);

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

//通过在<activity>标签下配置<intent-filter>的内容,可以指定当前活动能够响应的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>
//在<action>标签中我们指明了当前活动可以响应com.example.actvitytest.ACTION_START这个action,而<category>标签则包含了一些附加信息,更精确的指明了当前活动能够响应的Intent中还可能带有的category.只有<action><category>中的内容同时能够匹配上Intent中指定的action和category时,这个活动才能响应该Intent

Intent的使用:

Intent intent = new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);

因为android.intent.category.DEFAULT是一种默认的category,在调用startActivity()的时候会自动将这个category添加到Intent中.

每个Intent只能有一个action,但可以指定多个category.

//增加一个category
Intent intent = new Intent("com.example.activitytest.ACTION_START");
intent.addCategory("com.example.activitytest.MY_CATEGORY");
startActivity(intent);
//我们必须在<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>

3.更多隐式Intent的用法

//用浏览器打开网页
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
//与此对应,我们还可以在<intent-filter>标签中配置一个<data>标签,用于更精确的指定当前活动能够响应什么类型的数据
//android:scheme.用于指定数据的协议部分,如上面的http部分
//android:host.用于指定数据的主机名部分,如上面的www.baidu.com部分
//android:port.用于指定数据的端口部分,一般紧随在主机名之后
//android:path.用于指定主机名和端口之后的部分,如一段网址中跟在域名之后的内容
//android:mimeType.用于指定可以处理的数据类型,允许使用通配符的方式进行指定

例如:

<activity android:name = ".SecondActivity">
    <intent-filter>
        <action android:name="com.example.activitytest.ACTION_START"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:scheme="http"/>
    </intent-filter>
</activity>
//拨打电话
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值