Intent


背景

  • 「整理」在阅读跟「工作相关」的源码时遇到的「常见」的、「重要」的「数据结构」,方便透彻理解自己写的「代码背后」在干什么事情,代码不在于多而在于「精」
  • 尝试把「知识」分享给更多的人,锻炼对某个知识点真正理解的「能力」

是什么

  • 意图,目的
  • Intent 是 Android SDK 提供的一个数据结构,内部记录了即将要被执行的操作信息,基本上是一个实体类,不包含过多的业务逻辑,只是数据载体
  • 可以用于启动 Activity 、Service,发送广播信息给需要的 BroadcastReceiver,和后台 Service 进行通信

为什么

  • 解决的是 Android Component 间「通信」「信息载体」的问题

怎么样

使用方法

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

// 上述代码实际上只指定了 Intent.mComponent 字段,其它字段由接下来收到该 intent 消息的对象进行写入
  • 启动 Service
// 指定需要启动的 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_第1张图片
Intent 结构体

  • Intent 实现了 Parcelable 接口,说明该对象具备在多进程间传递的能力
  • 内部需要往 Parcel 里面读写的对象也需要实现 Parcelable 接口,如 ComponentName, Bundle 等
  • Bundle 类的数据由 mMap 字段记录

主要字段

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

优缺点

  • 高度封装 Android 进程间通信信息,降低上层应用的开发难度

练习题

  • 单步跟踪 Intent 对象的创建、传递流程,输出 UML 类图和时序图

总结

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

你可能感兴趣的:(Intent)