Intent

2017-08-25  本文已影响0人  1999c1b720cd

背景

是什么

为什么

怎么样

使用方法

// 在 java 堆上分配一个 intent 对象,并指定需要启动的组件的类型
Intent intent = new Intent(context, MainActivity.class);
//向 Context 对象发送 startActivity 消息
context.startActivity(intent); 

// 上述代码实际上只指定了 Intent.mComponent 字段,其它字段由接下来收到该 intent 消息的对象进行写入
// 指定需要启动的 Service 类的名称,方便接下来进行查找和实例化 Service 对象
String cls = PlayMusicService.class.getName();
// 指定包名
String pkg = context.getPackageName();
// 封装到 ComponentName 类中方便跨进程传递这两个信息
ComponentName component = new ComponentName(pkg, cls);
// 分配 intent 对象
Intent intent = new Intent();
// 写入组件名称信息
intent.setComponent(component);
// 向 Context 对象发送 startService 消息
context.startService(intent);
// 分配一个 bundle 对象, 用于记录附加数据
Bundle bundle = new Bundle();
// 向 bundle 写入要告诉接收者的信息
bundle.putString("key", "value");
// 分配一个 intent 对象
Intent intent = new Intent();
// 指定 action 字段,方便系统和接收者进行信息过滤
intent.setAction("com.passionli.action.data");
// 向 intent 写入附加数据
intent.putExtras(bundle);
// 向 Context 对象发送 sendBroadcast 消息,输入是 intent 对象
context.sendBroadcast(intent);

内部实现原理

UML 类图 Intent 结构体

主要字段

Field Type Description
mAction String 记录将要执行的行为,如查看联系人、打电话等
mData Uri 以 Uri 形式记录将要被操作的数据,如数据库中一个联系人、一张图片、一段视频等

例如:

Action Data Description
android.intent.action.VIEW content://contacts/people/1 「查看」「数据库中ID为1的联系人」的信息
android.intent.action.EDIT content://contacts/people/1 「编辑」「数据库中ID为1的联系人」的信息
android.intent.action.DIAL tel:123 「显示」「电话号码123」到拨号界面

类似 HTTP 协议中对「资源」进行 GET / POST / PUT / DELETE 等操作。

二级字段

Field Type Description
mCategories ArraySet<String> 记录 action 的「附加」信息
mType String 数据的 MIME 类型
mComponent ComponentName 指定处理该意图的组件
mExtras Bundle 一包/捆附加信息,发送给接收组件的额外的数据,如打开发送邮件界面并填充邮件的标题和主题数据等

优缺点

练习题

总结

以上是现阶段对 Intent 类的知识点整理,重点在于数据结构和内部实现原理的理解

上一篇 下一篇

猜你喜欢

热点阅读