4.5.1 Intent的基本使用
全面梳理 Android 组件通信枢纽 Intent 的七大属性、显式与隐式解析规则、intent-filter 匹配细节(含 CATEGORY_DEFAULT 与 setDataAndType),以及高频系统 Intent 速查与查阅路径。
学完这一章,你能够
- 全面梳理 Android 组件通信枢纽 Intent 的七大属性、显式与隐式解析规则、intent-filter 匹配细节(含 CATEGORY_DEFAULT 与 setDataAndType),以及高频系统 Intent 速查与查阅路径。
Intent 的枢纽角色、显式与隐式区别及七大属性
`Intent`(意图)是连接 Android 四大组件的通信枢纽,负责驱动 `startActivity()`/`startActivityForResult()`、`startService()`/`bindService()` 与 `sendBroadcast()`。按目标定位方式分为两类:显式 Intent 直接指明目标组件类(如 `new Intent(A.this, B.class)`),路由唯一确定,主要用于本应用内部跳转;隐式 Intent 不指定类名,而是描述要执行的动作与数据条件,交由系统逐一比对清单中的 `<intent-filter>`,命中多个目标时弹出选择器对话框供用户决定。
一个完整的 `Intent` 由七大属性组成:`ComponentName`(显式组件全限定名)、`Action`(动作字符串)、`Category`(类别附加限定,可多个)、`Data`(待操作数据的 URI)与 `Type`(MIME 数据类型,注意单独调用 `setData()` 会清空 `Type`,单独调用 `setType()` 会清空 `Data`,同时指定必须用 `setDataAndType()`)、`Extras`(附加键值 `Bundle`)以及 `Flags`(控制任务栈与启动行为的整型标志位)。
预定义与自定义隐式 Intent 的匹配规则实战
调用系统内置页面时,使用标准 Action 配合 Category 或 Data 即可:例如设置 `Intent.ACTION_MAIN` 搭配 `Intent.CATEGORY_HOME` 可直接返回手机桌面;设置 `Intent.ACTION_VIEW` 搭配 `Uri.parse("http://...")` 可唤起浏览器打开网页(注:原文将这两个示例归在“显式”小节标题下,从组件解析机制看它们未指定目标 `ComponentName`,实际属于由系统解析的隐式 Intent)。
在自定义 `<intent-filter>` 进行隐式匹配时,必须牢记两条核心规则:第一,Intent 携带的所有 `Category` 必须是目标 `<intent-filter>` 中声明的 Category 的子集;第二,调用 `startActivity()` 解析隐式 Intent 时,系统会自动向 Intent 附加 `android.intent.category.DEFAULT`。因此无论响应预定义 `android.intent.action.VIEW` 还是自定义 `my_action` + `my_category`,目标 `<activity>` 的 `<intent-filter>` 都必须补写 `<category android:name="android.intent.category.DEFAULT"/>`,否则必定匹配失败并抛出 `ActivityNotFoundException`。(此外在 Android 12+ 上包含 `<intent-filter>` 的组件必须显式声明 `android:exported`。)
常用系统 Intent 速查与官方文档查询方式
日常开发常复用的系统 Intent 涵盖拨号(`ACTION_DIAL` + `tel:`)、短信与彩信(`ACTION_SENDTO` / `ACTION_SEND`)、网页与地图定位(`ACTION_VIEW` + `http:`/`geo:`)、多媒体播放(`setDataAndType`)、拍照与相册选取(`MediaStore.ACTION_IMAGE_CAPTURE` / `ACTION_GET_CONTENT`)、应用商店与卸载(`market://` / `ACTION_DELETE`)、系统设置(`Settings.ACTION_WIRELESS_SETTINGS`)、联系人查看/编辑、录音机与网页搜索(`ACTION_WEB_SEARCH`)。跨应用传递文件时,Android 7.0(API 24)起禁止直接暴露 `file://` URI(会抛 `FileUriExposedException`),应改用 `FileProvider` 生成 `content://` URI 并授予临时读权限。如需查阅全部标准常量,可直接检索 SDK 本地参考文档 `docs/reference/android/content/Intent.html` 或 Android Developers 官网 `Intent` 参考页的 Constants 列表。
运行 Intent 七属性、setDataAndType 防清空、intent-filter 匹配引擎与 FileProvider 规则验证
展开查看收起
"""Offline Android Intent 7 attributes, explicit vs implicit intent-filter resolution, and system Intents verifier."""
import json
from urllib.parse import urlparse
VERSION = "CPython 3.12.14 offline Android component/IPC/Fragment verifier (Android SDK/emulator absent)"
class SimulatedIntent:
def __init__(self, component: str | None = None, action: str | None = None):
self.component = component
self.action = action
self.categories: set[str] = set()
self.data: str | None = None
self.mime_type: str | None = None
self.extras: dict = {}
self.flags: set[str] = set()
def set_data(self, uri: str):
# Android Intent.setData clears mime type
self.data = uri
self.mime_type = None
def set_type(self, mime: str):
# Android Intent.setType clears data URI
self.mime_type = mime
self.data = None
def set_data_and_type(self, uri: str, mime: str):
self.data = uri
self.mime_type = mime
def case_intent_seven_attributes_and_explicit_resolution():
# Verify Android setData/setType mutual-clearing trap vs setDataAndType
it = SimulatedIntent(action="android.intent.action.VIEW")
it.set_data("content://media/external/audio/1")
it.set_type("audio/mp3")
after_separate = (it.data, it.mime_type)
it.set_data_and_type("content://media/external/audio/1", "audio/mp3")
after_combined = (it.data, it.mime_type)
explicit = SimulatedIntent(component="com.demo.app.SecondActivity")
explicit.extras["id"] = 7
explicit.flags.add("FLAG_ACTIVITY_SINGLE_TOP")
actual = {
"seven_attributes": ["ComponentName", "Action", "Category", "Data", "Type", "Extras", "Flags"],
"after_separate_setData_then_setType": list(after_separate),
"after_setDataAndType": list(after_combined),
"explicit_bypasses_filter": explicit.component is not None,
}
expected = {
"seven_attributes": ["ComponentName", "Action", "Category", "Data", "Type", "Extras", "Flags"],
"after_separate_setData_then_setType": [None, "audio/mp3"],
"after_setDataAndType": ["content://media/external/audio/1", "audio/mp3"],
"explicit_bypasses_filter": True,
}
return {
"name": "intent_seven_attributes_and_explicit_resolution",
"summary": "验证 Intent 七大属性、显式指定 ComponentName 直接定位目标组件,以及 setData/setType 互相清空必须改用 setDataAndType 的关键规则。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_implicit_intent_filter_matcher():
activities = [
{
"name": "BrowserActivity",
"filters": [{
"actions": {"android.intent.action.VIEW"},
"categories": {"android.intent.category.DEFAULT", "android.intent.category.BROWSABLE"},
"schemes": {"http", "https"},
}],
},
{
"name": "SecondActivityView",
"filters": [{
"actions": {"android.intent.action.VIEW"},
"categories": {"android.intent.category.DEFAULT"},
"schemes": set(),
}],
},
{
"name": "SecondActivityCustom",
"filters": [{
"actions": {"my_action"},
"categories": {"my_category", "android.intent.category.DEFAULT"},
"schemes": set(),
}],
},
{
"name": "BrokenMissingDefaultActivity",
"filters": [{
"actions": {"broken_action"},
"categories": {"my_category"},
"schemes": set(),
}],
},
]
def resolve_start_activity(intent: SimulatedIntent) -> list[str]:
# startActivity automatically adds CATEGORY_DEFAULT to implicit Intents
req_cats = set(intent.categories) | {"android.intent.category.DEFAULT"}
scheme = urlparse(intent.data).scheme if intent.data else None
matches = []
for act in activities:
for flt in act["filters"]:
if intent.action not in flt["actions"]:
continue
if not req_cats.issubset(flt["categories"]):
continue
if flt["schemes"]:
if scheme not in flt["schemes"]:
continue
elif scheme is not None:
continue
matches.append(act["name"])
break
return matches
it_view_no_data = SimulatedIntent(action="android.intent.action.VIEW")
it_view_http = SimulatedIntent(action="android.intent.action.VIEW")
it_view_http.set_data("https://example.org")
it_custom = SimulatedIntent(action="my_action")
it_custom.categories.add("my_category")
it_broken = SimulatedIntent(action="broken_action")
it_broken.categories.add("my_category")
actual = {
"view_no_data": resolve_start_activity(it_view_no_data),
"view_https": resolve_start_activity(it_view_http),
"custom_with_default": resolve_start_activity(it_custom),
"missing_default_raises_not_found": len(resolve_start_activity(it_broken)) == 0,
}
expected = {
"view_no_data": ["SecondActivityView"],
"view_https": ["BrowserActivity"],
"custom_with_default": ["SecondActivityCustom"],
"missing_default_raises_not_found": True,
}
return {
"name": "implicit_intent_filter_matcher",
"summary": "验证隐式 Intent 对 Action、Category(含 startActivity 自动附加 DEFAULT)与 Data scheme 的匹配规则及缺失 DEFAULT 导致匹配失败。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_common_system_intents_catalog():
def validate_file_share(api_level: int, uri_scheme: str) -> str:
# Android 7.0+ (API 24) throws FileUriExposedException for file:// URIs shared across apps
if api_level >= 24 and uri_scheme == "file":
return "FileUriExposedException -> use FileProvider content:// URI"
return "ALLOWED"
home_intent = {"action": "android.intent.action.MAIN", "category": "android.intent.category.HOME"}
dial_intent = {"action": "android.intent.action.DIAL", "data": "tel:10086"}
search_intent = {"action": "android.intent.action.WEB_SEARCH", "extra_query": "Android Intent"}
actual = {
"home_intent_valid": home_intent["action"].endswith("MAIN") and home_intent["category"].endswith("HOME"),
"dial_uri_scheme": urlparse(dial_intent["data"]).scheme,
"search_query": search_intent["extra_query"],
"api24_file_uri_share": validate_file_share(24, "file"),
"api24_content_uri_share": validate_file_share(24, "content"),
}
expected = {
"home_intent_valid": True,
"dial_uri_scheme": "tel",
"search_query": "Android Intent",
"api24_file_uri_share": "FileUriExposedException -> use FileProvider content:// URI",
"api24_content_uri_share": "ALLOWED",
}
return {
"name": "common_system_intents_catalog",
"summary": "验证返回桌面、拨号、搜索等常用系统 Intent 构造,并核对 Android 7.0+ (API 24) 禁止直接跨应用传递 file:// URI 需改用 FileProvider 的演进。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_intent_seven_attributes_and_explicit_resolution(),
case_implicit_intent_filter_matcher(),
case_common_system_intents_catalog(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 Android 框架在 startActivity() 和 startActivityForResult() 内部会自动为所有隐式 Intent 附加 android.intent.category.DEFAULT,若目标过滤器的 Category 集合未包含该默认值,匹配将失败并抛出 ActivityNotFoundException。