蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Intent 七属性、setDataAndType 防清空、intent-filter 匹配引擎与 FileProvider 规则验证

PYTHONWindows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。explore-tutorial-intent-base.py
explore-tutorial-intent-base.py198 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。

入口文件:projects/android-tutorial-intent-base-lab/explore-tutorial-intent-base.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-intent-base.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1907.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习