详解Android Intent uri的语法规则

394 阅读2分钟

前言

IntentURI 语法是 Android 中用于序列化 Intent 的一种格式。它可以将 Intent 的所有属性(如 actiondataextras 等)封装为一个字符串,从而方便传递和解析。

基本格式

intent:#Intent;[attributes];end
  • intent::标识符,表示这是一个 Intent URI。
  • #Intent:固定标识,用于分隔 URI 中的数据部分。
  • [attributes]:具体的 Intent 属性和值(如 action、data 等)。
  • end:固定结束标识符。

支持的属性

1. action

  • 用于指定 Intent 的操作。
  • 格式:action=<ACTION_STRING>
  • 示例:action=android.intent.action.VIEW

2. data

  • 用于指定 Intent 的数据(URI 格式)。
  • 格式:data=<DATA_URI>
  • 示例:data=https://example.com

3. type

  • 用于指定数据的 MIME 类型。
  • 格式:type=<MIME_TYPE>
  • 示例:type=image/jpeg

4. component

  • 指定 Intent 的目标组件。
  • 格式:component=<PACKAGE_NAME>/<CLASS_NAME>
  • 示例:component=com.example.app/com.example.app.MainActivity

5. categories

  • 指定 Intent 的类别。
  • 格式:category=<CATEGORY_NAME>
  • 示例:category=android.intent.category.DEFAULT

6. extras

-用于指定附加数据(键值对),支持多种数据类型。

  • 格式:
    • 字符串:S.<key>=<value>
    • 整型:i.<key>=<value>
    • 浮点型:f.<key>=<value>
    • 布尔型:B.<key>=<value> (true 或 false)
    • 长整型:l.<key>=<value>
    • 短整型:s.<key>=<value>
    • 字节数组:b.<key>=<hex_value>
  • 示例:
    • S.username=john_doe
    • i.age=30
    • B.isAdmin=true

7. launchFlags

  • 指定 Intent 的启动标志。
  • 格式:launchFlags=<HEX_VALUE>
  • 示例:launchFlags=0x10000000(对应 Intent.FLAG_ACTIVITY_NEW_TASK)

8. package

  • 指定应用的包名。
  • 格式:package=<PACKAGE_NAME>
  • 示例:package=com.example.app

完整示例

intent:#Intent;action=android.intent.action.VIEW;data=https://example.com;type=text/html;component=com.example.app/com.example.app.MainActivity;category=android.intent.category.BROWSABLE;S.username=john_doe;i.age=25;B.isAdmin=true;launchFlags=0x10000000;end

对应Intent结构

val intent = Intent().apply {
    action = "android.intent.action.VIEW"
    data = Uri.parse("https://example.com")
    type = "text/html"
    setClassName("com.example.app", "com.example.app.MainActivity")
    addCategory("android.intent.category.BROWSABLE")
    putExtra("username", "john_doe")
    putExtra("age", 25)
    putExtra("isAdmin", true)
    flags = Intent.FLAG_ACTIVITY_NEW_TASK
}

解析规则

使用 Intent.parseUri() 方法可以解析该格式的 URI 并生成 Intent 对象。 示例代码:

val uri = "intent:#Intent;action=android.intent.action.VIEW;data=https://example.com;type=text/html;S.username=john_doe;i.age=25;end"
val intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME)

注意事项

  1. flags 的格式:必须为十六进制(以 0x 开头)。
  2. 键名和类型前缀的区分:不同数据类型需要使用不同的前缀(如 S 表示字符串,i 表示整型)。
  3. 目标组件安全性:解析并启动 Intent 时,需要验证目标组件是否可信,以避免安全漏洞。
  4. 数据和类型的兼容性datatype 必须能匹配,否则可能导致 ActivityNotFoundException
  5. 版本兼容:某些属性可能在较老的 Android 版本中不支持(如 flags 的一些值)。

总结

通过 Intent URI可以非常方便地序列化和反序列化 Intent,使其能够在不同组件之间传递甚至跨应用使用。