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

运行 Android Studio Gradle 目录树、向导 applicationId 校验、模板 Manifest 绑定及 Kotlin DSL 对照

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-android-studio.py
explore-tutorial-android-studio.py181 行
"""Offline deterministic verifier for Android CH05 (tutorial-android-studio)."""
from __future__ import annotations

import json
import re
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path

ANDROID_NS = "{http://schemas.android.com/apk/res/android}"


def case_gradle_project_structure() -> dict:
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp) / "MyFirstASApp"
        required = [
            "settings.gradle.kts",
            "build.gradle.kts",
            "gradle.properties",
            "app/build.gradle.kts",
            "app/src/main/AndroidManifest.xml",
            "app/src/main/java/com/example/hello/MainActivity.java",
            "app/src/main/res/layout/activity_main.xml",
            "app/src/main/res/values/strings.xml",
        ]
        for rel in required:
            p = root / rel
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text("ok", encoding="utf-8")
        actual = {
            "all_required_present": all((root / r).is_file() for r in required),
            "module_name": "app",
            "gradle_files": sum(1 for r in required if "gradle" in r),
        }
    expected = {
        "all_required_present": True,
        "module_name": "app",
        "gradle_files": 4,
    }
    return {
        "name": "gradle_project_structure_verifier",
        "summary": "生成并核验 Android Studio 标准 Gradle 工程及 app 模块核心目录文件",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_wizard_app_id_and_sdk() -> dict:
    app_name = "HelloStudio"
    company_domain = "mbsky.example.com"
    reversed_domain = ".".join(reversed(company_domain.split(".")))
    app_id = f"{reversed_domain}.{app_name.lower()}"
    sdk = {"minSdk": 21, "targetSdk": 34, "compileSdk": 34}
    id_valid = bool(re.fullmatch(r"[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+", app_id))
    sdk_valid = sdk["minSdk"] <= sdk["targetSdk"] <= sdk["compileSdk"]
    actual = {
        "application_id": app_id,
        "id_valid": id_valid,
        "sdk_order_valid": sdk_valid,
        "form_factors": ["Phone and Tablet", "Wear OS", "Android TV"],
    }
    expected = {
        "application_id": "com.example.mbsky.hellostudio",
        "id_valid": True,
        "sdk_order_valid": True,
        "form_factors": ["Phone and Tablet", "Wear OS", "Android TV"],
    }
    return {
        "name": "wizard_app_id_and_sdk_constraints",
        "summary": "校验新建向导域名反写 applicationId 规范及 minSdk<=targetSdk<=compileSdk 约束",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_activity_template_binding() -> dict:
    manifest = """<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mbsky.hellostudio">
    <application android:label="@string/app_name">
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>"""
    layout = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" />
</LinearLayout>"""
    m_root = ET.fromstring(manifest)
    l_root = ET.fromstring(layout)
    act = m_root.find("application/activity")
    assert act is not None
    actual = {
        "activity_name": act.attrib[f"{ANDROID_NS}name"],
        "root_layout_tag": l_root.tag,
        "child_widget_tags": [c.tag for c in l_root],
        "has_launcher": any(
            c.attrib.get(f"{ANDROID_NS}name") == "android.intent.category.LAUNCHER"
            for c in act.findall("intent-filter/category")
        ),
    }
    expected = {
        "activity_name": ".MainActivity",
        "root_layout_tag": "LinearLayout",
        "child_widget_tags": ["TextView"],
        "has_launcher": True,
    }
    return {
        "name": "activity_template_xml_manifest_binding",
        "summary": "验证新建 Activity 模板生成的 Manifest 入口声明与 XML 布局树绑定一致性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_groovy_to_kotlin_dsl() -> dict:
    groovy_snippet = """android {
    compileSdkVersion 34
    defaultConfig {
        applicationId "com.example.mbsky.hellostudio"
        minSdkVersion 21
        targetSdkVersion 34
    }
}"""
    kts_snippet = """android {
    namespace = "com.example.mbsky.hellostudio"
    compileSdk = 34
    defaultConfig {
        applicationId = "com.example.mbsky.hellostudio"
        minSdk = 21
        targetSdk = 34
    }
}"""
    g_min = int(re.search(r"minSdkVersion\s+(\d+)", groovy_snippet).group(1))
    k_min = int(re.search(r"minSdk\s*=\s*(\d+)", kts_snippet).group(1))
    g_id = re.search(r'applicationId\s+"([^"]+)"', groovy_snippet).group(1)
    k_id = re.search(r'applicationId\s*=\s*"([^"]+)"', kts_snippet).group(1)
    actual = {
        "min_sdk_match": g_min == k_min == 21,
        "app_id_match": g_id == k_id == "com.example.mbsky.hellostudio",
        "kts_has_namespace": 'namespace = "com.example.mbsky.hellostudio"' in kts_snippet,
    }
    expected = {
        "min_sdk_match": True,
        "app_id_match": True,
        "kts_has_namespace": True,
    }
    return {
        "name": "groovy_to_kotlin_dsl_build_config",
        "summary": "对比传统 Groovy build.gradle 与现代 Kotlin DSL build.gradle.kts 核心构建坐标",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Android XML/layout/manifest verifier (Android SDK/emulator absent)",
        "cases": [
            case_gradle_project_structure(),
            case_wizard_app_id_and_sdk(),
            case_activity_template_binding(),
            case_groovy_to_kotlin_dsl(),
        ],
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-android-studio.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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