Android Intent

xiaoxiao2021-02-28  161

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);
转载请注明原文地址: https://www.6miu.com/read-19209.html

最新回复(0)