Android中有四大组件来构成Android程序,Intent是Android程序中三大组件(活动,广播,服务)之间传递消息的一种重要方式,它不仅可以指明当前组件想要执行的动作,还可以在不同组件间传递数据。Intent一般可被用于启动活动、启动服务以及发送广播等场景,这是Intent重要的几个用途。总体来说,Intent是一种运行时绑定(run-time binding)机制,它能在程序运行过程中连接两个不同的组件。
Intent大致可以分为两种类型:显式Intent和隐式Intent。
显式Intent:
如果在我们定义的Intent中明确包含了要启动的组件的完整类名(包名及类名),即Intent的“意图”非常明显,那么这个Intent就是显式的。使用显式Intent最典型的情形是在你自己的程序中启动一个组件,因为你自己肯定知道自己的要启动的组件的类名。比如,为了响应用户操作通过显式的Intent在你的程序中启动一个Activity或启动一个Service下载文件。
隐式Intent:
没有明确指定组件名要启动哪一个活动,而是系统根据动作(action)、类别(category)、数据(Uri)和数据类型来找到最合适的组件。一般来说我们需要在<intent-filter>里设置category、action和data等信息。需要注意的是,为了确保App的安全性,我们应该总是使用显式Intent去启动Service并且不要为该Service设置任何的Intent Filter。通过隐式的Intent启动Service是有风险的,因为你不确定最终哪个App中的哪个Service会启动起来以响应你的隐式Intent,更悲催的是,由于Service没有UI的在后台运行,所以用户也不知道哪个Service运行了
Intent Filter,即Intent过滤器,一个组件可以包含0个或多个Intent Filter。Intent Filter是写在App的manifest文件中的,其通过设置action或uri数据类型等指明了组件能够处理接收的Intent的类型。对于Android的主活动都有下面几行代码来表明启动活动:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
例子:对于隐式Intent的具体方法:
在AndroidManifest.xml中定义相应的activity代码:
<activity
android:name=".ThreeActivity"
>
<intent-filter >
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="http"/>
</intent-filter>
</activity>
其中<action>标签指明了当前活动可以响应的action。<category>标签则附加了一些信息,更精确地指明了当前活动能响应的Intent还可能带有的category。只有<action>和<category>同时匹配上Intent中指定的action和category时,活动才能响应该Intent。
<data>标签能够更精确地指定当前活动能够响应什么类型的数据。<data>标签中主要可以配置一下内容:
android:scheme。用于指定数据的协议部分,如http
android:host。用于指定数据的主机名部分
android:port。用于指定数据的端口部分,一般在主机名之后
android:path。用于指定主机名和端口之后的部分,如一段网址中跟在域名之后的内容
android:mimeType。用于指定可以处理的数据类型,允许使用通配符的方式进行指定
只用当<data>标签中指定的内容和Intent中携带的data部分完全一致时,当前活动才能够响应intent。
Intent intent=new Intent("android.intent.action.VIEW");
intent.addCategory("com.example.as_menu.MY_CATEGORY");
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
Intent传输数据:
批量传参
Intent intent = newIntent();
Bundle bundle = newBundle();
bundle.putString("name","NSU");
intent.putExtra("bundle",bundle);
intent.putExtras(bundle);
逐个传参
Intent intent = newIntent();
intent.putExtra("name", "NSU");
intent.putExtra("age", 10);
Intent接收数据:
批量接收
Bundle bundle =getIntent().getBundleExtra("bundle");
String name =bundle.getString("name");
int age =bundle.getInt("age");
Bundle bundle =getIntent.getExtras();
逐个接收
Intent intent =getIntent();
String name =intent.getStringExtra("name");
int age =intent.getIntExtra("age");