ios-to-android
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseThis skill guides you through the structured process of migrating an Apple iOS
application to modern Android. It provides an end-to-end 10-step engineering
methodology that performs deep pre-flight project discovery, establishes Gradle
infrastructure, and conditionally loads specialized reference documents from
based on the specific subsystems detected in the source codebase.
references/本 Skill 指导你以结构化流程将 Apple iOS 应用迁移到现代 Android。它提供一套端到端的 10 步工程方法,执行深入的迁移前项目发现、搭建 Gradle 基础设施,并根据源代码库中检测到的具体子系统,有条件地从 加载专门的参考文档。
references/Objective
目标
To systematically convert an iOS codebase into a clean, modern, and idiomatic
Android application powered by Jetpack Compose , Kotlin Coroutines &
Flow , and Android Architecture Components, maintaining architectural
integrity and visual parity without legacy Android view bloat, unverified
stubbing, or proprietary vendor lock-in.
系统地将 iOS 代码库转换为整洁、现代且符合 Android 惯用实践的应用程序,由 Jetpack Compose、Kotlin Coroutines 与 Flow 和 Android Architecture Components 驱动;在保持架构完整性与视觉一致性的同时,避免遗留旧式 Android View 冗余、未经验证的 stub 或专有供应商锁定。
Operational Scope Modes
操作范围模式
Before taking action, determine which operational mode matches the user's
request and workspace:
采取行动之前,请确定与用户请求和工作区相匹配的操作模式:
Mode A: Full Application Migration (End-to-End Greenfield)
模式 A:完整应用迁移(端到端全新开发)
- Trigger: The user asks to migrate an entire iOS application from start to finish, or the target directory is empty / contains only a clean starter skeleton.
- Workflow: Execute the full 10-step methodology sequentially (Steps 1 through 10), decomposing the app into multi-package architecture, establishing build configuration, porting all subsystems, and verifying against the final consolidated build gate.
- Mandatory Pre-Migration Subsystem Inspection Gate : Before implementing Android code for any detected iOS domain capability, you MUST explicitly view and inspect the corresponding reference guide in for each subsystem present in the source codebase:
references/- Architecture & State : Inspect references/architecture-and-viewmodels.md and references/state-and-reactive-flows.md.
- Screen Layouts & Declarative UI : Inspect references/ui-layout-swiftui-to-compose.md.
- Navigation : Inspect references/navigation-compose.md.
- Database & Entities : Inspect references/database-coredata-to-room.md.
- Preferences & Settings : Inspect references/preferences-datastore.md.
- Runtime Permissions : Inspect references/permissions-runtime.md.
- Health & Fitness : Inspect references/health-connect.md.
- In-App Billing & Store : Inspect references/in-app-billing.md.
- Bluetooth LE Sensors : Inspect references/bluetooth-ble.md.
- Location & GPS Tracking : Inspect references/location-fusedprovider.md.
- Background Tasks : Inspect references/background-tasks-workmanager.md.
[!IMPORTANT] Important: This gate is mandatory. Readingalone is not sufficient to complete a migration --- this root document is an index and a set of invariants; the reference guides hold the actual API-level implementation patterns. Skipping them is the single most common cause of mock-stub managers, missing runtime permissions, and non-idiomatic layouts that compile cleanly and then fail review.SKILL.md
You MUST record the list of reference guides you actually opened in
under a
heading. If a subsystem is present in the source app and its guide is absent
from that list, the migration is incomplete --- go back and read it before
concluding.
.migration/migration_walkthrough.md## Reference Guides Consulted- 触发条件:用户要求从头到尾迁移整个 iOS 应用,或者目标目录为空/仅包含一个干净的起始骨架。
- 工作流:依次执行完整的 10 步方法(步骤 1 至步骤 10),将应用拆分为多包架构、建立构建配置、移植所有子系统,并通过最终合并后的构建关卡进行验证。
- 强制迁移前子系统检查关卡:在为检测到的任何 iOS 领域能力实现 Android 代码之前,对于源代码库中存在的每个子系统,你必须明确查看并检查 中对应的参考指南:
references/- 架构与状态:检查 references/architecture-and-viewmodels.md 和 references/state-and-reactive-flows.md。
- 屏幕布局与声明式 UI:检查 references/ui-layout-swiftui-to-compose.md。
- 导航:检查 references/navigation-compose.md。
- 数据库与实体:检查 references/database-coredata-to-room.md。
- 偏好与设置:检查 references/preferences-datastore.md。
- 运行时权限:检查 references/permissions-runtime.md。
- 健康与健身:检查 references/health-connect.md。
- 应用内计费与商店:检查 references/in-app-billing.md。
- Bluetooth LE 传感器:检查 references/bluetooth-ble.md。
- 位置与 GPS 跟踪:检查 references/location-fusedprovider.md。
- 后台任务:检查 references/background-tasks-workmanager.md。
[!IMPORTANT] **重要:**此关卡是强制性的。 仅阅读不足以完成迁移——本根文档只是索引和一组不变量;真正的 API 级实现模式位于参考指南中。跳过它们是 mock-stub manager、缺失运行时权限,以及虽能干净编译却在评审时失败的非惯用布局的最常见原因。SKILL.md
你必须在 的 标题下记录实际打开的参考指南列表。如果源应用中存在某个子系统,但其指南未出现在该列表中,则迁移尚未完成——必须返回并阅读对应指南,然后才能结束。
.migration/migration_walkthrough.md## Reference Guides ConsultedMode B: Scoped Sub-Component & Feature Migration (Contextual Integration)
模式 B:范围受限的子组件与功能迁移(上下文集成)
- Trigger : The user asks to migrate a specific subsystem, feature, screen, or capability (e.g., CoreData to Room, HealthKit to Health Connect, StoreKit to Play Billing, BLE, or a specific screen) into an existing Android project.
- Bypass Macro Overhead : Do NOT perform a full 10-step audit of the entire iOS repository or generate a full .
.migration/feature_specification.md - Execute the 4-Phase Micro Workflow :
- Target Codebase Convention Discovery: Inspect the target Android project to discover and adopt established architecture, package structure, dependency injection, and state patterns.
- Surgical Subsystem Routing : Jump directly to the relevant supplemental reference guide in for the requested capability.
references/ - Scoped Migration & Integration: Implement the subsystem matching the discovered target conventions and wire it to replace any existing Fakes or stubs.
- Targeted Build & Test Verification : Verify or run specific unit tests without mutating unrelated modules.
./gradlew assembleDebug
- Anti-Premature-Exit & Execution Liveness Mandate :
- NEVER exit or yield prematurely on background tasks : If a build or test command (,
./gradlew assembleDebug) runs asynchronously, do NOT output a passive waiting message (such as "Waiting for tests to complete..." ) without pending tool calls. In non-interactive runs, ending a turn with no pending tool call ends the task before the build finishes. Either wait synchronously (./gradlew test) or monitor the task to completion.WaitMsBeforeAsync: 10000 - A task is NEVER finished without the implementation diff : You must author or update the target Kotlin source files (,
write_to_file) replacing mock/stub implementations with real Android Jetpack/platform APIs before concluding.replace_file_content
- NEVER exit or yield prematurely on background tasks : If a build or test command (
- 触发条件:用户要求将特定子系统、功能、屏幕或能力(例如 CoreData 到 Room、HealthKit 到 Health Connect、StoreKit 到 Play Billing、BLE 或某个具体屏幕)迁移到现有 Android 项目中。
- 绕开宏观开销:不要对整个 iOS 仓库执行完整的 10 步审计,也不要生成完整的 。
.migration/feature_specification.md - 执行四阶段微工作流:
- 目标代码库约定发现:检查目标 Android 项目,发现并采用其既有架构、包结构、依赖注入和状态模式。
- 精准子系统路由:直接进入 中与所请求能力对应的补充参考指南。
references/ - 范围受限的迁移与集成:按照发现的目标约定实现子系统,并将其接入以替换现有的 Fakes 或 stubs。
- 针对性构建与测试验证:执行 或运行特定单元测试,且不得修改无关模块。
./gradlew assembleDebug
- 禁止提前退出与执行活性要求:
- 绝不提前退出或在后台任务上无谓暂停:如果构建或测试命令(、
./gradlew assembleDebug)异步运行,在没有待处理工具调用的情况下,不要输出“正在等待测试完成……”之类的被动等待消息。在非交互式运行中,如果在没有待处理工具调用的情况下结束回合,任务会在构建完成前终止。你应当同步等待(./gradlew test)或持续监控任务直至完成。WaitMsBeforeAsync: 10000 - 没有实现 diff,任务绝不视为完成:结束前,你必须编写或更新目标 Kotlin 源文件(、
write_to_file),以真实的 Android Jetpack/平台 API 替换 mock/stub 实现。replace_file_content
- 绝不提前退出或在后台任务上无谓暂停:如果构建或测试命令(
Target Codebase Convention Discovery Protocol (Mandatory for Mode B)
目标代码库约定发现协议(模式 B 强制执行)
When performing a sub-component migration into an existing Android codebase, you
MUST inspect 2--3 existing files in and
before creating or modifying files. Adopt the target
project's established conventions across these 5 dimensions:
app/src/main/java/gradle/libs.versions.toml- Package Organization :
- Layer-based (,
data/,domain/) vs. Feature-based (ui/,feature/home/). Place new files into the existing package hierarchy rather than inventing an incompatible tree.feature/catalog/
- Layer-based (
- Dependency Injection & Service Locator :
- Discover how dependencies are provided: Hilt (,
@Inject,@HiltViewModel), Koin , or manual AppContainer / Service Locator pattern.@InstallIn - Do NOT introduce a foreign DI framework . If the target app uses manual DI or an , provide clean constructor injections that plug directly into that container. If it uses Hilt, provide Hilt
AppContainerand@Modulebindings.@Provides
- Discover how dependencies are provided: Hilt (
- State Management & Concurrency :
- Observe how ViewModels expose UI state: unified data classes, individual StateFlows, or Compose
StateFlow<UiState>.MutableState - Observe how Coroutine dispatchers are provided (e.g., injected vs
@IoDispatcher).Dispatchers.IO
- Observe how ViewModels expose UI state: unified
- Design System & UI Components :
- Inspect and common component directories. If the codebase defines custom composable wrappers (e.g.
ui/theme/,AppButton, custom typography tokens), reuse them rather than falling back to generic default primitives.AppCard
- Inspect
- Version Catalog & Dependencies :
- Inspect before adding dependencies. If a library family (e.g. Room, Coroutines, Serialization) already exists, reuse the project's existing versions and aliases instead of adding duplicates.
gradle/libs.versions.toml
- Inspect
在现有 Android 代码库中执行子组件迁移时,你必须在创建或修改文件之前,检查 中的 2--3 个现有文件以及 。你必须在这 5 个维度上采用目标项目的既有约定:
app/src/main/java/gradle/libs.versions.toml- 包组织方式:
- 基于层级(、
data/、domain/)还是基于功能(ui/、feature/home/)。将新文件放入现有包层级,而不是创建不兼容的目录树。feature/catalog/
- 基于层级(
- 依赖注入与服务定位器:
- 发现依赖的提供方式:Hilt(、
@Inject、@HiltViewModel)、Koin,或手动 AppContainer/Service Locator 模式。@InstallIn - 不要引入外部的 DI 框架。如果目标应用使用手动 DI 或 ,请提供可直接接入该容器的干净构造函数注入。如果使用 Hilt,则提供 Hilt
AppContainer和@Module绑定。@Provides
- 发现依赖的提供方式:Hilt(
- 状态管理与并发:
- 观察 ViewModel 如何暴露 UI 状态:统一的 data class、独立的 StateFlow,或 Compose
StateFlow<UiState>。MutableState - 观察 Coroutine dispatcher 的提供方式,例如注入 还是直接使用
@IoDispatcher。Dispatchers.IO
- 观察 ViewModel 如何暴露 UI 状态:统一的
- 设计系统与 UI 组件:
- 检查 和公共组件目录。如果代码库定义了自定义 composable 包装器,例如
ui/theme/、AppButton或自定义排版 token,应复用它们,而不是退回到通用默认 primitive。AppCard
- 检查
- 版本目录与依赖项:
- 添加依赖项之前检查 。如果某个库系列(例如 Room、Coroutines、Serialization)已经存在,应复用项目现有版本和 alias,而不是添加重复项。
gradle/libs.versions.toml
- 添加依赖项之前检查
Summary of the 10-Step Migration Methodology (Mode A)
10 步迁移方法摘要(模式 A)
- Deep Source Audit, Domain Discovery & Migration Brief
- Subsystem & Capability Decomposition
- Formulate and Approve Phased Migration Plan
- Project Infrastructure, Gradle & DI Initialization (Mandatory Build Gate 1)
- Resource Catalog & Localization Migration
- Local Persistence & Storage Migration (Mandatory Build Gate 2)
- Core Architecture, Concurrency, State Hoisting & Secrets Handling
- Declarative UI & Navigation Porting to Jetpack Compose (Mandatory Build Gate 3)
- Hardware, Platform Services & Background Subsystems
- Build Verification, Test Porting, Quality Triage & Walkthrough Generation (Mandatory Build Gate 4)
- 深入源审计、领域发现与迁移简报
- 子系统与能力拆分
- 制定并确认分阶段迁移计划
- 项目基础设施、Gradle 与 DI 初始化(强制构建关卡 1)
- 资源目录与本地化迁移
- 本地持久化与存储迁移(强制构建关卡 2)
- 核心架构、并发、状态提升与密钥处理
- 向 Jetpack Compose 移植声明式 UI 与导航(强制构建关卡 3)
- 硬件、平台服务与后台子系统
- 构建验证、测试移植、质量分流与迁移说明生成(强制构建关卡 4)
Detailed Migration Steps
详细迁移步骤
Step 1: Deep Source Audit, Domain Discovery & Migration Brief
步骤 1:深入源审计、领域发现与迁移简报
Before writing any Android code, you Must perform an exhaustive audit of the
iOS source tree.
- Domain Grounding : Deduce the application's true functional purpose (e.g., finance, healthcare, social, productivity) from actual code, data models, and API integrations. Do NOT guess visual motifs or architectures based solely on the app's name.
- Deep Functional Extraction: Pay close attention to all functionality implemented in the source application, including non-obvious logic, background tasks, state synchronization, data flows, and lifecycle edge cases. Do not skim the surface.
- Structure & Dependencies : Discover targets with and inventory dependencies via
find . -maxdepth 3 -type d,Podfile, orPackage.swift.Cartfile - Generate Migration Brief : Produce a formal in
feature_specification.mdsummarizing all features, entry/exit points, data flows, and Android target equivalents..migration/ - Consult references/analysis-and-project-audit.md for full audit checklists and the Migration Brief specification template.
编写任何 Android 代码之前,你必须对 iOS 源码树执行全面审计。
- 领域定位:根据实际代码、数据模型和 API 集成,推断应用的真实功能用途,例如金融、医疗、社交或生产力。不要仅根据应用名称猜测视觉主题或架构。
- 深度功能提取:密切关注源应用中实现的所有功能,包括不明显逻辑、后台任务、状态同步、数据流和生命周期边缘情况。不要只浏览表层功能。
- 结构与依赖项:使用 发现目标目录,并通过
find . -maxdepth 3 -type d、Podfile或Package.swift盘点依赖项。Cartfile - 生成迁移简报:在 中生成正式的
.migration/,概述所有功能、入口与出口、数据流以及 Android 目标对应物。feature_specification.md - 查阅 references/analysis-and-project-audit.md,了解完整的审计检查清单和迁移简报规范模板。
Step 2: Subsystem & Capability Decomposition
步骤 2:子系统与能力拆分
Map detected iOS capabilities to Android replacement frameworks. Use the
Heuristic Routing Table below to determine which supplemental reference
guides are required for the project. When conducting a full-app migration (Mode
A), you MUST inspect the corresponding reference guide for every subsystem
detected in the iOS app before writing implementation code.
将检测到的 iOS 能力映射到 Android 替代框架。使用下面的启发式路由表确定项目需要哪些补充参考指南。执行完整应用迁移(模式 A)时,在编写实现代码之前,你必须检查 iOS 应用中检测到的每个子系统所对应的参考指南。
Heuristic Routing Table (Progressive Disclosure)
启发式路由表(渐进式披露)
| Detected iOS Indicator / Code Pattern | Supplemental Reference Guide | Android Target Architecture |
|---|---|---|
| references/ui-layout-swiftui-to-compose.md | Jetpack Compose (LazyColumn, Row, Column, Box) |
| references/database-coredata-to-room.md | Jetpack Room, SQLite, KSP |
| references/location-fusedprovider.md | FusedLocationProviderClient / LocationManager |
| references/in-app-billing.md | Google Play Billing Library 8 |
| references/health-connect.md | Jetpack Health Connect |
| references/bluetooth-ble.md | Android BLE GATT & Scanner |
| references/camera-camerax.md | Jetpack CameraX (PreviewView, ImageAnalysis) |
| references/push-notifications-fcm.md | NotificationManager & FCM |
| references/background-tasks-workmanager.md | Android WorkManager (CoroutineWorker) |
| references/preferences-datastore.md | Jetpack Preferences DataStore |
| references/navigation-compose.md | Navigation Compose with Type-Safe Routing |
| references/ui-animations.md | Jetpack Compose Animation APIs |
| references/testing-unit-and-compose.md | JUnit5, MockK, ComposeTestRule |
| references/screenshots-screengrab.md | Fastlane Screengrab, UI Automator |
| 检测到的 iOS 标识/代码模式 | 补充参考指南 | Android 目标架构 |
|---|---|---|
| references/ui-layout-swiftui-to-compose.md | Jetpack Compose(LazyColumn、Row、Column、Box) |
| references/database-coredata-to-room.md | Jetpack Room、SQLite、KSP |
| references/location-fusedprovider.md | FusedLocationProviderClient / LocationManager |
| references/in-app-billing.md | Google Play Billing Library 8 |
| references/health-connect.md | Jetpack Health Connect |
| references/bluetooth-ble.md | Android BLE GATT 与 Scanner |
| references/camera-camerax.md | Jetpack CameraX(PreviewView、ImageAnalysis) |
| references/push-notifications-fcm.md | NotificationManager 与 FCM |
| references/background-tasks-workmanager.md | Android WorkManager(CoroutineWorker) |
| references/preferences-datastore.md | Jetpack Preferences DataStore |
| references/navigation-compose.md | Navigation Compose 与类型安全路由 |
| references/ui-animations.md | Jetpack Compose Animation APIs |
| references/testing-unit-and-compose.md | JUnit5、MockK、ComposeTestRule |
| references/screenshots-screengrab.md | Fastlane Screengrab、UI Automator |
Universal Platform Capability & ActivityResultContract Matrix
通用平台能力与 ActivityResultContract 矩阵
On Android, different system capabilities require distinct runtime invocation
mechanisms. When porting iOS system dialogs and authorization flows, you
MUST use the dedicated Android contract rather than generic permission
requests:
| iOS Framework / Capability | Android Runtime Mechanism | Dedicated Android Contract / API |
|---|---|---|
Standard Runtime Permissions ( | Activity Result Launcher | |
HealthKit ( | Health Connect Permission Contract | |
Photo Library ( | Activity Result Photo Picker | |
Document Picker ( | Storage Access Framework | |
In-App Purchases / Subscriptions ( | Play Billing Flow | |
| Android 14+ Foreground Services | Manifest Service Declaration | `<service android:foregroundServiceType="health |
[!IMPORTANT] Important: Android 14+ (API 34+) Manifest & Foreground Service Rules : 1. Foreground Service Types : Anytag in<service>that runs in the foreground MUST specifyAndroidManifest.xmlmatching the exact permissions and functionality used (e.g.android:foregroundServiceType,health,location,dataSync,camera). Omitting this attribute will trigger a runtimeconnectedDeviceon Android 14+. 2.SecurityExceptionHealthKit Mapping (Info.plist/NSHealthShareUsageDescription) : Always map iOS HealthKit privacy keys inNSHealthUpdateUsageDescriptionto Android 14+ Health Connect permissions (AndroidManifest.xml,android.permission.health.READ_STEPS,android.permission.health.READ_HEART_RATE, etc.) alongsideandroid.permission.health.READ_ACTIVE_CALORIES_BURNED.<queries><package android:name="com.google.android.apps.healthdata" /></queries>
在 Android 上,不同系统能力需要采用不同的运行时调用机制。移植 iOS 系统对话框和授权流程时,你必须使用专用的 Android contract,而不是通用权限请求:
| iOS 框架/能力 | Android 运行时机制 | 专用 Android Contract/API |
|---|---|---|
标准运行时权限( | Activity Result Launcher | |
HealthKit( | Health Connect Permission Contract | |
照片图库( | Activity Result Photo Picker | |
文档选择器( | Storage Access Framework | |
应用内购买/订阅( | Play Billing Flow | |
| Android 14+ 前台服务 | Manifest Service Declaration | `<service android:foregroundServiceType="health |
[!IMPORTANT] **重要:**Android 14+(API 34+)Manifest 与前台服务规则:1. 前台服务类型:中任何在前台运行的AndroidManifest.xml标签都必须指定<service>,并与所使用的权限和功能完全匹配,例如android:foregroundServiceType、health、location、dataSync、camera。在 Android 14+ 上省略此属性会触发运行时connectedDevice。2.SecurityExceptionHealthKit 映射(Info.plist/NSHealthShareUsageDescription):始终将 iOS HealthKit 隐私键映射到NSHealthUpdateUsageDescription中 Android 14+ 的 Health Connect 权限(AndroidManifest.xml、android.permission.health.READ_STEPS、android.permission.health.READ_HEART_RATE等),并同时添加android.permission.health.READ_ACTIVE_CATEGORIES_BURNED。<queries><package android:name="com.google.android.apps.healthdata" /></queries>
Step 3: Formulate and Approve Phased Migration Plan
步骤 3:制定并确认分阶段迁移计划
Generate a structured Migration Assessment Report and migration backlog based on
Steps 1 and 2.
- Detail the module breakdown, dependencies in , and sequential execution milestones.
libs.versions.toml - Explicitly identify any proprietary or closed-source iOS APIs that lack 1:1 Android mappings, and document the fallback strategy (see Unsupported Element Protocol in references/analysis-and-project-audit.md).
- IF interactive user approval is supported, ask for confirmation before modifying or generating code.
- ELSE, proceed directly to Step 4 following the generated plan.
根据步骤 1 和步骤 2,生成结构化的迁移评估报告和迁移任务清单。
- 详细说明模块拆分、中的依赖项以及顺序执行里程碑。
libs.versions.toml - 明确识别缺少 1:1 Android 对应物的专有或闭源 iOS API,并记录回退策略,参见 references/analysis-and-project-audit.md 中的 Unsupported Element Protocol。
- 如果交互式用户确认机制可用,在修改或生成代码之前请求用户确认。
- 否则,根据生成的计划直接进入步骤 4。
Contextual Architectural Scaling (By App Size & Complexity)
按应用规模与复杂度进行架构调整
Before generating Android source files, evaluate the scale and complexity of the
iOS source project and select the appropriate structural tier:
- Tier 1: Micro-Apps, Single-Feature Utilities, or Scoped Prototypes (<
1,000 LOC / 1--2 Screens)
- Consolidation Permitted: When migrating a small, self-contained utility or single-screen component, consolidating domain models, state holders, and Compose UI into a compact package or single cohesive file is acceptable when it improves readability and avoids over-engineering.
- Tier 2: Multi-Feature Production Applications (> 1,000 LOC / 5+ Screens /
Multiple Subsystems such as CoreData, BLE, HealthKit, Maps)
- Full Architectural Decomposition Mandatory : When migrating a complex, multi-journey application (such as a production app), you MUST NOT collapse the application into a single monolithic file () or substitute functional screens with barebones test-tag stubs.
MainActivity.kt - Mandatory Multi-Package Execution Protocol for Complex Apps :
- Package Decomposition : Organize code into logical packages (,
data/local/,data/preferences/,domain/model/,ui/navigation/,ui/screens/).ui/theme/must only initializeMainActivity.kt, runtime permission launchers, and the rootenableEdgeToEdge()scaffold.NavHost - Complete Local Persistence (&
data/local/) : Implement concretedata/preferences/classes for all core domain tables (e.g., both the catalog entity and the user-history entity), a@Entityinterface exposing@Daoqueries, and aFlow<List<T>>. Implement asynchronousRoomDatabasefor user settings and authentication tokens.DataStore<Preferences> - Extracted Android Resources (&
res/values/strings.xml) : Extract user-facing strings intoui/theme/Theme.ktand define both Light and Dark Material 3res/values/strings.xmls inColorScheme.Theme.kt - Complete Navigation Graph () : Build a
ui/navigation/NavGraph.ktcovering both top-level bottom navigation tabs (NavHost,launchSingleTop = true) AND distinct sub-flow destinations (e.g. onboarding, detail screens, full-screen task flows). Model onboarding / first-run flows as destinations inside thatrestoreState = true(choose the start destination from the persisted "onboarding complete" flag); never render them as a separate composable tree outside theNavHostthat callsNavHostbefore the graph has been set, which throws at runtime.navController.navigate(...) - Runtime Permission Launchers : In addition to declaring the Android 14+ permissions for each capability the source app uses in , invoke
AndroidManifest.xmlat runtime in the Compose UI layer.rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) - Feature-Complete Material 3 Screens () : Every screen must collect state from a Jetpack
ui/screens/*.ktviaViewModel(never rawcollectAsStateWithLifecycle()), render scrollable lists usingcollectAsState()with explicitLazyColumnparameters, and present Material 3 content showing the real domain data from the source app's models (not placeholder text), matching the functional specification.key = { ... }
- Package Decomposition : Organize code into logical packages (
- Full Architectural Decomposition Mandatory : When migrating a complex, multi-journey application (such as a production app), you MUST NOT collapse the application into a single monolithic file (
生成 Android 源文件之前,评估 iOS 源项目的规模和复杂度,并选择合适的结构层级:
- 第 1 层:微型应用、单功能工具或范围受限的原型(< 1,000 LOC/1--2 个屏幕)
- 允许合并:迁移小型、自包含的工具或单屏幕组件时,如果能够提升可读性并避免过度工程化,可以将领域模型、状态持有者与 Compose UI 合并到紧凑的包或单个内聚文件中。
- 第 2 层:多功能生产应用(> 1,000 LOC/5 个以上屏幕/包含多个子系统,例如 CoreData、BLE、HealthKit、Maps)
- 强制完整架构拆分:迁移复杂、多流程应用(例如生产应用)时,你不得将整个应用折叠成单个巨型文件(),也不得使用只有测试标签的简陋 stub 来替代功能屏幕。
MainActivity.kt - 复杂应用强制多包执行协议:
- 包拆分:按逻辑组织代码(、
data/local/、data/preferences/、domain/model/、ui/navigation/、ui/screens/)。ui/theme/只能负责初始化MainActivity.kt、运行时权限 launcher 和根级enableEdgeToEdge()脚手架。NavHost - 完整的本地持久化(与
data/local/):为所有核心领域表实现具体的data/preferences/类,例如目录 entity 和用户历史 entity;实现暴露@Entity查询的Flow<List<T>>接口,以及@Dao。使用异步RoomDatabase保存用户设置和认证 token。DataStore<Preferences> - 提取 Android 资源(与
res/values/strings.xml):将面向用户的字符串提取到ui/theme/Theme.kt,并在res/values/strings.xml中定义 Light 与 Dark Material 3Theme.kt。ColorScheme - 完整导航图():构建覆盖所有顶层底部导航标签(
ui/navigation/NavGraph.kt、launchSingleTop = true)以及不同子流程目的地(例如 onboarding、详情屏幕、全屏任务流程)的restoreState = true。将 onboarding/首次运行流程建模为NavHost内的目的地,根据持久化的“onboarding complete”标志选择起始目的地;绝不要在图尚未设置时,在NavHost外部渲染单独的 composable 树并调用NavHost,否则会在运行时抛出异常。navController.navigate(...) - 运行时权限 Launcher:除了在 中声明源应用使用的每项能力所需的 Android 14+ 权限外,还必须在运行时于 Compose UI 层调用
AndroidManifest.xml。rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) - 功能完整的 Material 3 屏幕():每个屏幕都必须通过
ui/screens/*.kt从 JetpackcollectAsStateWithLifecycle()收集状态,绝不能使用原始ViewModel;使用带有明确collectAsState()参数的key = { ... }渲染可滚动列表;使用 Material 3 展示来自源应用模型的真实领域数据,而不是占位文本,并符合功能规范。LazyColumn
- 包拆分:按逻辑组织代码(
- 强制完整架构拆分:迁移复杂、多流程应用(例如生产应用)时,你不得将整个应用折叠成单个巨型文件(
Step 4: Project Infrastructure, Gradle & DI Initialization
步骤 4:项目基础设施、Gradle 与 DI 初始化
Inspect the target Android directory before touching build configuration files:
- IF an Android project shell already exists (i.e. ,
settings.gradle.kts,build.gradle.kts, andapp/build.gradle.ktsare present):MainActivity.kt- DO NOT generate wholly new project files or overwrite , root
settings.gradle.kts, orbuild.gradle.ktsfrom scratch.app/build.gradle.kts - MUST PRESERVE the existing ,
namespace, and root package name (e.g., keepapplicationIdin its existing root package and place all new sub-packages---MainActivity.kt,data/local/,data/preferences/,domain/model/,ui/navigation/,ui/screens/---under that same root package).ui/theme/ - Incremental Gradle Updates Only : Modify and
app/build.gradle.ktsto add all Jetpack and Google Play libraries required for the detected iOS capabilities immediately in Step 4 before authoring manager classes. Never remove existing dependencies, plugins, or test configuration you did not add.gradle/libs.versions.toml - Mandatory Subsystem Dependencies in :
app/build.gradle.kts- If HealthKit () is detected: set
import HealthKitinminSdk = 26and adddefaultConfig {}andimplementation("androidx.health.connect:connect-client:1.1.0-alpha07")toimplementation("com.google.guava:guava:33.0.0-android").dependencies {} - If StoreKit () is detected: add
import StoreKittoimplementation("com.android.billingclient:billing-ktx:8.3.0").dependencies {} - If BGTaskScheduler () is detected: add
import BackgroundTaskstoimplementation("androidx.work:work-runtime-ktx:2.9.0").dependencies {} - If CoreLocation () is detected: add
import CoreLocationtoimplementation("com.google.android.gms:play-services-location:21.2.0").dependencies {}
- If HealthKit (
- DO NOT generate wholly new project files or overwrite
- ELSE (if starting in an empty directory with no Gradle files) :
- Initialize the target Android project structure with Kotlin DSL (,
settings.gradle.kts,build.gradle.kts) and establish module boundaries matching iOS targets.gradle/libs.versions.toml
- Initialize the target Android project structure with Kotlin DSL (
- Consult references/project-setup-and-gradle.md and references/dependency-injection-hilt.md.
修改构建配置文件之前,检查目标 Android 目录:
- 如果已经存在 Android 项目骨架(即存在 、
settings.gradle.kts、build.gradle.kts和app/build.gradle.kts):MainActivity.kt- 不要生成全新的项目文件,也不要从头覆盖 、根
settings.gradle.kts或build.gradle.kts。app/build.gradle.kts - 必须保留现有的 、
namespace和根包名。例如,将applicationId保留在现有根包中,并把所有新的子包——MainActivity.kt、data/local/、data/preferences/、domain/model/、ui/navigation/、ui/screens/——放在同一根包下。ui/theme/ - 仅增量更新 Gradle:修改 和
app/build.gradle.kts,在编写 manager 类之前,立即加入检测到的 iOS 能力所需的全部 Jetpack 和 Google Play 库。绝不能移除你没有添加的现有依赖项、插件或测试配置。gradle/libs.versions.toml - 中必须包含对应子系统的依赖项:
app/build.gradle.kts- 如果检测到 HealthKit():在
import HealthKit中设置defaultConfig {},并在minSdk = 26中添加dependencies {}和implementation("androidx.health.connect:connect-client:1.1.0-alpha07")。implementation("com.google.guava:guava:33.0.0-android") - 如果检测到 StoreKit():在
import StoreKit中添加dependencies {}。implementation("com.android.billingclient:billing-ktx:8.3.0") - 如果检测到 BGTaskScheduler():在
import BackgroundTasks中添加dependencies {}。implementation("androidx.work:work-runtime-ktx:2.9.0") - 如果检测到 CoreLocation():在
import CoreLocation中添加dependencies {}。implementation("com.google.android.gms:play-services-location:21.2.0")
- 如果检测到 HealthKit(
- 不要生成全新的项目文件,也不要从头覆盖
- 否则(如果从空目录开始且没有任何 Gradle 文件):
- 使用 Kotlin DSL(、
settings.gradle.kts、build.gradle.kts)初始化目标 Android 项目结构,并建立与 iOS 目标相对应的模块边界。gradle/libs.versions.toml
- 使用 Kotlin DSL(
- 查阅 references/project-setup-and-gradle.md 和 references/dependency-injection-hilt.md。
Step 5: Resource Catalog & Localization Migration
步骤 5:资源目录与本地化迁移
Extract and convert iOS asset catalogs and strings into Android resource
directories.
- Convert image assets and vector drawings in into Android XML Drawables.
.xcassets - Map app icons to adaptive icons.
res/mipmap-anydpi-v26/ic_launcher.xml - Convert into
Localizable.strings.res/values/strings.xml - Consult references/resources-and-assets.md.
提取并将 iOS 资源目录与字符串转换为 Android 资源目录。
- 将 中的图像资源和矢量图转换为 Android XML Drawable。
.xcassets - 将应用图标映射到 自适应图标。
res/mipmap-anydpi-v26/ic_launcher.xml - 将 转换为
Localizable.strings。res/values/strings.xml - 查阅 references/resources-and-assets.md。
Step 6: Local Persistence & Storage Migration
步骤 6:本地持久化与存储迁移
Port data models, local relational databases, and key-value preferences.
- IF Core Data / SwiftData is detected, map entities, type converters, and DAOs to Room using references/database-coredata-to-room.md.
- IF or
UserDefaultsis detected, replace with Preferences DataStore using references/preferences-datastore.md.@AppStorage - Initial Database Seeding : If the iOS app ships bundled or preloaded data (sample records, catalog items, defaults), you MUST seed it on first launch. Otherwise list and detail screens render empty states and the app looks broken on first launch.
- Default strategy --- seeding : Read the iOS seed data (bundled JSON/plist, Swift sample-data arrays, or rows extracted at migration time from a bundled database such as a Core Data / SwiftData / GRDB / FMDB
RoomDatabase.Callbackor a Realm file) and insert equivalent domain rows through your DAOs in.sqlite. This cannot fail Room's schema validation.onCreate() - NEVER copy a bundled iOS database file (Core Data / SwiftData / GRDB /
FMDB ) verbatim into
.sqliteand pass it toassets/unless everycreateFromAsset()was deliberately written to mirror that file's exact@Entitytables, columns, types, nullability and indices (see references/database-coredata-to-room.md). Room validates pre-packaged databases on first open and throwsZ*, crashing the app on launch. Adding extra tables to the copied file does not fix this.IllegalStateException: Pre-packaged database has an invalid schema - You usually cannot observe this crash (no device/emulator; still succeeds). If you do use
assembleDebug, you MUST statically prove schema parity before finishing, using the no-device verification in section 0, "Choose a seeding strategy before writing entities", of references/database-coredata-to-room.md.createFromAsset()
- Default strategy ---
- Room Threading : Room throws for any query on the main thread. Make DAO methods
IllegalStateExceptionor returnsuspend; never call the database from a ViewModelFlowbody, from composition, or insideinit {}on the main thread --- launch the work inrunBlocking(or a repository coroutine onviewModelScope) instead. Run seeding from theDispatchers.IOon a background dispatcher. Never useRoomDatabase.Callbackin production code (it is acceptable only in tests).allowMainThreadQueries()
移植数据模型、本地关系数据库和键值偏好设置。
- 如果检测到 Core Data/SwiftData,请使用 references/database-coredata-to-room.md 将实体、类型转换器和 DAO 映射到 Room。
- 如果检测到 或
UserDefaults,请使用 references/preferences-datastore.md 将其替换为 Preferences DataStore。@AppStorage - 初始数据库种子数据:如果 iOS 应用附带预加载数据(示例记录、目录项、默认值),你必须在首次启动时完成播种。否则列表和详情屏幕会呈现空状态,应用在首次启动时看起来像是损坏的。
- 默认策略——播种:读取 iOS 种子数据(内置 JSON/plist、Swift sample-data 数组,或迁移时从 Core Data/SwiftData/GRDB/FMDB
RoomDatabase.Callback或 Realm 文件等内置数据库提取的行),并通过 DAO 在.sqlite中插入对应的领域行。这样不会导致 Room schema 校验失败。onCreate() - 绝不将内置 iOS 数据库文件(Core Data/SwiftData/GRDB/FMDB )原样复制到
.sqlite并传给assets/,除非每个createFromAsset()都经过刻意编写,以完整镜像该文件的@Entity表、列、类型、可空性和索引,参见 references/database-coredata-to-room.md。Room 会在首次打开时校验预打包数据库,并抛出Z*,导致应用启动崩溃。向复制文件添加额外表并不能解决问题。IllegalStateException: Pre-packaged database has an invalid schema - 你通常无法观察到该崩溃(没有设备/模拟器;仍会成功)。如果确实使用
assembleDebug,则必须在结束前按照 references/database-coredata-to-room.md 第 0 节“选择播种策略后再编写实体”中的无设备验证方法,从静态角度证明 schema 完全一致。createFromAsset()
- 默认策略——
- Room 线程处理:Room 会在主线程执行任何查询时抛出 。将 DAO 方法设为
IllegalStateException或返回suspend;绝不能从 ViewModel 的Flow、composition 内部或主线程上的init {}中调用数据库——应在runBlocking中启动工作,或在 repository coroutine 中通过viewModelScope执行。播种应从Dispatchers.IO在后台 dispatcher 上运行。绝不要在生产代码中使用RoomDatabase.Callback,它仅可在测试中使用。allowMainThreadQueries()
Step 7: Core Architecture, Concurrency, State Hoisting & Secrets Handling
步骤 7:核心架构、并发、状态提升与密钥处理
Translate business logic, network services, reactive state management, and
external API configurations.
- Map CocoaPods / Swift Package Manager libraries and Swift /
asyncto Kotlin Coroutines using references/dependencies-and-concurrency.md.await - Convert ObservableObjects into Android instances with
ViewModelusing references/architecture-and-viewmodels.md.SavedStateHandle - Convert ,
@State, and Combine publishers into@Binding,mutableStateOf, andStateFlowwithSharedFlowusing references/state-and-reactive-flows.md.collectAsStateWithLifecycle - MANDATORY LIFECYCLE AWARENESS : When observing ViewModel or
StateFlowstreams inside Jetpack Compose screens, ALWAYS useSharedFlowfromcollectAsStateWithLifecycle(). NEVER use standardandroidx.lifecycle.compose.collectAsStateWithLifecycle.collectAsState()does not pause collection when the application is backgrounded or the screen is off, leaking resources and draining battery by keeping sensors, database queries, and network flows active.collectAsState() - Mandatory Named Arguments for Dependency Wiring : When instantiating repositories, use cases, and ViewModels in or
AppContainer.kt, always use Kotlin named arguments (e.g.MainActivity.kt). This eliminates swapped parameter compilation errors between the class definition and its call site.ItemRepository(context = this, api = api) - API Keys & Secrets Rules : Never hardcode secrets in source code. Place API keys into and read them via Gradle
local.propertiesor secure credential providers.buildConfigField
转换业务逻辑、网络服务、响应式状态管理和外部 API 配置。
- 使用 references/dependencies-and-concurrency.md 将 CocoaPods/Swift Package Manager 库和 Swift /
async映射到 Kotlin Coroutines。await - 使用 references/architecture-and-viewmodels.md 将 ObservableObjects 转换为使用 的 Android
SavedStateHandle实例。ViewModel - 使用 references/state-and-reactive-flows.md 将 、
@State和 Combine publisher 转换为@Binding、mutableStateOf和StateFlow,并结合SharedFlow使用。collectAsStateWithLifecycle - 强制生命周期感知:在 Jetpack Compose 屏幕中观察 ViewModel 的 或
StateFlow流时,始终使用SharedFlow中的androidx.lifecycle.compose.collectAsStateWithLifecycle。绝不要使用标准collectAsStateWithLifecycle()。collectAsState()不会在应用进入后台或屏幕关闭时暂停收集,从而持续消耗资源并通过保持传感器、数据库查询和网络流活跃而浪费电量。collectAsState() - 依赖接线强制使用命名参数:在 或
AppContainer.kt中实例化 repository、use case 和 ViewModel 时,始终使用 Kotlin 命名参数,例如MainActivity.kt。这样可以避免类定义与调用点之间参数顺序互换导致编译错误。ItemRepository(context = this, api = api) - API Key 与密钥规则:绝不能将密钥硬编码到源代码中。将 API Key 放入 ,并通过 Gradle
local.properties或安全凭据提供程序读取。buildConfigField
Step 8: Declarative UI & Navigation Porting to Jetpack Compose
步骤 8:向 Jetpack Compose 移植声明式 UI 与导航
Rebuild user interface screens and navigation hierarchies in Jetpack Compose.
- Material 3 Semantic Theming & Color Encapsulation :
- NEVER reference un-scoped top-level color constants directly inside screen composables (e.g. referencing loose ). This causes unresolved reference errors across packages and breaks theme adaptability.
val CustomBrandBlue = Color(...) - Map all branding and palette colors extracted from iOS asset catalogs () directly into the
Assets.xcassetsdefinition inColorScheme(using standard slots likeui/theme/Theme.kt,primary,secondary,tertiary,surface,surfaceVariant) or into a customerrorprovided viaExtendedColorScheme.CompositionLocalProvider - In screen composables, access colors strictly via or semantic design system tokens. This guarantees zero missing imports across any package and automated Dark/Light theme switching.
MaterialTheme.colorScheme.<slot>
- NEVER reference un-scoped top-level color constants directly inside screen composables (e.g. referencing loose
- Mandatory Edge-to-Edge : Implement on the host Activity and properly handle
enableEdgeToEdge()across all composable screens.WindowInsets - Compose Previews : Every top-level composable screen MUST include a matching function to enable visual validation.
@Preview - Implement type-safe screen routing and bottom navigation using references/navigation-compose.md.
- Replicate layout transitions, physics-based springs, and shared elements using references/ui-animations.md.
- Jetpack Compose Runtime Permission Protocol :
- In Jetpack Compose applications, runtime permissions MUST be requested inside screens using
@Composable(orrememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())for Health Connect).PermissionController.createRequestPermissionResultContract() - NEVER fall back to legacy Activity-level inside
registerForActivityResult()unless there is no composable-compliant permission alternative available for that specific platform capability.MainActivity.kt - NEVER simulate platform permissions with mock boolean flags in repositories or bypass real permission checks.
- In Jetpack Compose applications, runtime permissions MUST be requested inside
- Compose Layout Anti-Squeeze Invariant : In every that places flexible content (a title/description
RoworText) beside fixed-intent elements (aColumn, price or badgeButton,Text,FilterChip,SegmentedButton,IconButton), applySwitchto the flexible side andModifier.weight(1f)to the fixed element'smaxLines = 1; otherwise Compose squeezes the fixed element and wraps its label one character per line on a typical phone width (roughly 360--411dp).Textis not a substitute for a weight. Put multi-option selectors (segmented buttons, chip groups) on their own full-width row below the section title, each optionArrangement.SpaceBetween. Worked examples: references/ui-layout-swiftui-to-compose.md.Modifier.weight(1f) - String Resources Are Referenced, Not Just Declared : SwiftUI is an implicit
Text("Literal")lookup; ComposeLocalizedStringKeyis not. Every user-facing string --- text, button and chip labels, titles,Text("Literal"), snackbar/dialog text, and custom-componentcontentDescription/text/titlearguments, including strings the iOS code wrote inline --- must come fromlabel. AstringResource(R.string....)the UI never references does not count. Also:strings.xml- Strings first, per screen : before writing each composable, add that screen's user-facing strings to --- the iOS view's inline literals as well as its localized keys (
strings.xml,String(localized:), or generated accessors such as SwiftGen'sNSLocalizedString/ R.swift), reusing existing entries --- then write the composable againstL10nkeys. Don't defer extraction to a clean-up pass.R.string - Dynamic text uses format arguments , never concatenation or string templates (→
<string name="trail_distance">Distance: %1$s</string>); concatenated fragments cannot be translated or reordered.stringResource(R.string.trail_distance, distance) - Display names on models and enums (goals, categories, levels) hold a resolved in the UI, not a raw
@StringRes Int.String - Text outside composition (notifications, toasts, foreground-service notifications, widgets) uses .
context.getString(...) - Previews, log messages and non-user-facing keys (routes, test tags, channel IDs) are exempt.
- Strings first, per screen : before writing each composable, add that screen's user-facing strings to
使用 Jetpack Compose 重建用户界面屏幕和导航层级。
- Material 3 语义主题与颜色封装:
- 绝不要在屏幕 composable 内直接引用未限定作用域的顶层颜色常量,例如引用独立的 。这会导致跨包的未解析引用错误,并破坏主题适配能力。
val CustomBrandBlue = Color(...) - 将从 iOS 资源目录()提取的所有品牌色和调色板颜色直接映射到
Assets.xcassets中的ui/theme/Theme.kt定义,使用ColorScheme、primary、secondary、tertiary、surface、surfaceVariant等标准槽位,或映射到通过error提供的自定义CompositionLocalProvider。ExtendedColorScheme - 在屏幕 composable 中,严格通过 或语义设计系统 token 访问颜色。这样可以保证跨包引用时不会出现缺失 import,并支持自动进行 Dark/Light 主题切换。
MaterialTheme.colorScheme.<slot>
- 绝不要在屏幕 composable 内直接引用未限定作用域的顶层颜色常量,例如引用独立的
- 强制 Edge-to-Edge:在宿主 Activity 中实现 ,并在所有 composable 屏幕中正确处理
enableEdgeToEdge()。WindowInsets - Compose Preview:每个顶层 composable 屏幕都必须包含匹配的 函数,以支持视觉验证。
@Preview - 使用 references/navigation-compose.md 实现类型安全的屏幕路由与底部导航。
- 使用 references/ui-animations.md 复刻布局转场、基于物理的弹簧动画和共享元素。
- Jetpack Compose 运行时权限协议:
- 在 Jetpack Compose 应用中,运行时权限必须在 屏幕内通过
@Composable请求;Health Connect 则使用rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())。PermissionController.createRequestPermissionResultContract() - 绝不要回退到 中旧式的 Activity 级
MainActivity.kt,除非该特定平台能力不存在任何符合 Compose 规范的权限替代方案。registerForActivityResult() - 绝不要在 repository 中使用 mock boolean 标志模拟平台权限,也不得绕过真实权限检查。
- 在 Jetpack Compose 应用中,运行时权限必须在
- Compose 布局防挤压不变量:在每个 中,如果固定意图元素(
Row、价格或徽标Button、Text、FilterChip、SegmentedButton、IconButton)旁放置了可伸缩内容(标题/描述Switch或Text),必须对可伸缩一侧应用Column,并对固定元素的Modifier.weight(1f)设置Text;否则在典型手机宽度(约 360--411dp)下,Compose 会挤压固定元素,使其标签逐字符换行。maxLines = 1不能替代Arrangement.SpaceBetween。多选项选择器(segmented button、chip group)应放在标题下方的独立全宽行中,并为每个选项应用weight。可参考 references/ui-layout-swiftui-to-compose.md 中的示例。Modifier.weight(1f) - 字符串资源必须被引用,而不只是声明:SwiftUI 的 隐式执行
Text("Literal")查找,而 Compose 的LocalizedStringKey不会。每个面向用户的字符串——文本、按钮和 chip 标签、标题、Text("Literal")、snackbar/dialog 文本,以及自定义组件的contentDescription/text/title参数,包括 iOS 代码内联写入的字符串——都必须来自label。UI 从未引用的stringResource(R.string....)不算完成。同时:strings.xml- 按屏幕优先处理字符串:编写每个 composable 之前,先将该屏幕面向用户的字符串添加到 ——包括 iOS 视图中的内联字面量和本地化键(
strings.xml、String(localized:),或 SwiftGen 的NSLocalizedString/R.swift 等生成的 accessor)——并复用已有条目——然后使用L10n键编写 composable。不要将提取工作推迟到最后清理阶段。R.string - 动态文本使用格式参数,绝不能使用字符串拼接或模板(→
<string name="trail_distance">Distance: %1$s</string>);拼接的片段无法翻译或重新排序。stringResource(R.string.trail_distance, distance) - 模型和枚举上的显示名称(目标、类别、等级)保存 ,并在 UI 中解析,而不是保存原始
@StringRes Int。String - Composition 之外的文本(通知、toast、前台服务通知、widget)使用 。
context.getString(...) - Preview、日志消息和非面向用户的键(路由、测试标签、channel ID)不受此限制。
- 按屏幕优先处理字符串:编写每个 composable 之前,先将该屏幕面向用户的字符串添加到
Step 9: Hardware, Platform Services & Background Subsystems
步骤 9:硬件、平台服务与后台子系统
Conditionally load and execute domain-specific platform services when identified
during Step 2:
- Runtime Permissions : Consult references/permissions-runtime.md for the iOS → Android 14+ permission mapping table, the
Info.plisthook pattern, Health Connect's dedicated permission contract, and the two-step background location flow. Every dangerous permission declared inrememberPermissionRequestrequires a matching runtime request --- a manifest entry alone grants nothing, and the request must surface the real system dialog rather than an in-app substitute.AndroidManifest.xml - Camera : Consult references/camera-camerax.md for CameraX preview (inside Compose
PreviewView) andAndroidView.ImageCapture - Location & Geofencing : Consult references/location-fusedprovider.md for Google Play Fused Location Provider and runtime permission flows.
- Bluetooth LE : Consult references/bluetooth-ble.md for BLE scanning and GATT callbacks.
- In-App Billing : Consult references/in-app-billing.md for Google Play Billing Library 8.
- Health & Fitness : Consult references/health-connect.md for Health Connect data types and permissions.
- Push & Local Notifications : Consult references/push-notifications-fcm.md for Notification Channels, Android 13+ permissions, and FCM.
- Background Tasks : Consult references/background-tasks-workmanager.md for constraints and periodic jobs.
WorkManager
[!CAUTION] Caution: Non-Negotiable Real Platform SDK Contract (Never Write Pure Mock Managers) : iOS codebases often include Simulator fallbacks or dummy data inside their platform-service managers (for example HealthKit, CoreBluetooth, StoreKit, CoreLocation, background tasks, camera, push notifications, MapKit or CloudKit). When migrating (including full-app Mode A migrations), you MUST NOT replace platform SDKs with pure mock timers or. Implement the real Android SDK in each manager/service class. Wrap hardware/SDK calls inSharedPreferencesso JVM unit tests and devices without the hardware or SDK don't crash; this covers missing hardware , never missing permissions --- check the permission first, then call insidetry/catch. Sample/demo data is allowed only as a fallback when the SDK is unavailable or the user denies permission: never mixed into real results, and never granting an entitlement. If the source gates sample/demo data behind a user setting, debug flag ortry/catch, port that gate (a DataStore preference or#if targetEnvironment(simulator)); never call a demo-data loader unconditionally fromBuildConfig.DEBUGor from a scan/read entry point. 1. Runtime permissions : see Runtime Permission Invariants below.initis not a permission implementation; it is allowed only on a call site guarded by@SuppressLint("MissingPermission"). 2. Health Connect :ContextCompat.checkSelfPermission(...) == PackageManager.PERMISSION_GRANTED,HealthConnectClient.getOrCreate(context)/HealthPermission.getReadPermission(...)for the record types matching the HealthKit types the source app reads and writes,getWritePermission(...)andreadRecords(ReadRecordsRequest(...)). See references/health-connect.md. 3. Google Play Billing :insertRecords(...); aBillingClient.newBuilder(context).setListener(purchasesUpdatedListener).enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()).build()whoseBillingClientStateListeneractually reconnects (for example with exponential backoff, or reconnect-on-next-request) rather than only logging;onBillingServiceDisconnected(),queryProductDetailsAsync, andlaunchBillingFlow(activity, params). Placeholder prices may be displayed as a fallback, but a purchase with no ready client or no Activity fails --- delete mock purchase code rather than keeping it as anacknowledgePurchasebranch. See references/in-app-billing.md. 4. Bluetooth LE :else→BluetoothManagerwith a concreteBluetoothLeScanner.startScan(filters, settings, scanCallback), and a concreteScanCallback(BluetoothGattCallback,onConnectionStateChange,onServicesDiscoveredparsing the GATT characteristics the iOS code reads). Manifest:onCharacteristicChanged(withBLUETOOTH_SCANunless location is derived from scans) andandroid:usesPermissionFlags="neverForLocation", both requested at runtime; legacyBLUETOOTH_CONNECT/BLUETOOTHand any scan-onlyBLUETOOTH_ADMINlimited withACCESS_FINE_LOCATION. See references/bluetooth-ble.md. 5. Location :android:maxSdkVersion="30"withLocationServices.getFusedLocationProviderClient(context)and aLocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMillis)(LocationCallback/requestLocationUpdates). When tracking must continue after the UI leaves the screen (iOSremoveLocationUpdates/allowsBackgroundLocationUpdates), add aUIBackgroundModes: locationthat callsServicewith an ongoing notification, declared withstartForegroundplusandroid:foregroundServiceType="location"andFOREGROUND_SERVICE. Don't declareFOREGROUND_SERVICE_LOCATIONunless a code path reads location with no visible UI and no foreground service; never declare permissions the migrated code doesn't use. See references/location-fusedprovider.md. 6. WorkManager : aACCESS_BACKGROUND_LOCATIONscheduled withCoroutineWorker, mirroring the iOS task's cadence and constraints. See references/background-tasks-workmanager.md.WorkManager.getInstance(context).enqueueUniquePeriodicWork(..., ExistingPeriodicWorkPolicy.KEEP, PeriodicWorkRequestBuilder<...>(...).setConstraints(...).build())
根据步骤 2 中识别出的结果,有条件地加载并执行特定领域平台服务:
- 运行时权限:查阅 references/permissions-runtime.md,了解 iOS 到 Android 14+ 权限映射表、
Info.plisthook 模式、Health Connect 专用 permission contract,以及分两步进行的后台定位流程。rememberPermissionRequest中声明的每项危险权限都必须有对应的运行时请求——仅声明 Manifest 条目不会授予任何权限,请求必须呈现真实的系统对话框,而不是应用内替代界面。AndroidManifest.xml - 相机:查阅 references/camera-camerax.md,了解 CameraX 预览(Compose 中的 内嵌
AndroidView)和PreviewView。ImageCapture - 位置与地理围栏:查阅 references/location-fusedprovider.md,了解 Google Play Fused Location Provider 和运行时权限流程。
- Bluetooth LE:查阅 references/bluetooth-ble.md,了解 BLE 扫描和 GATT callback。
- 应用内计费:查阅 references/in-app-billing.md,了解 Google Play Billing Library 8。
- 健康与健身:查阅 references/health-connect.md,了解 Health Connect 数据类型和权限。
- 推送与本地通知:查阅 references/push-notifications-fcm.md,了解 Notification Channel、Android 13+ 权限和 FCM。
- 后台任务:查阅 references/background-tasks-workmanager.md,了解 WorkManager 约束和周期性任务。
[!CAUTION] 注意:****不可妥协的真实平台 SDK 契约(绝不编写纯 Mock Manager):iOS 代码库通常会在平台服务 manager 中包含 Simulator fallback 或 dummy data,例如 HealthKit、CoreBluetooth、StoreKit、CoreLocation、后台任务、相机、推送通知、MapKit 或 CloudKit。迁移时,包括完整的模式 A 迁移,你不得使用纯 mock timer 或替换平台 SDK。必须在每个 manager/service 类中实现真实的 Android SDK。使用SharedPreferences包装硬件/SDK 调用,使 JVM 单元测试以及缺少硬件或 SDK 的设备不会崩溃;这只用于处理缺少硬件,绝不能用于绕过缺少权限——应先检查权限,然后在try/catch中调用。示例/demo 数据仅允许在 SDK 不可用或用户拒绝权限时作为 fallback;绝不能将其混入真实结果,也绝不能授予 entitlement。如果源代码通过用户设置、debug flag 或try/catch控制示例/demo 数据,则应移植该开关(使用 DataStore 偏好或#if targetEnvironment(simulator));绝不能从BuildConfig.DEBUG或扫描/读取入口无条件调用 demo data loader。1. 运行时权限:参见下方的运行时权限不变量。init不是权限实现;只有在调用位置受@SuppressLint("MissingPermission")保护时才允许使用。2. Health Connect:使用ContextCompat.checkSelfPermission(...) == PackageManager.PERMISSION_GRANTED;针对与源应用读写 HealthKit 类型相匹配的记录类型,使用HealthConnectClient.getOrCreate(context)/HealthPermission.getReadPermission(...)、getWritePermission(...)和readRecords(ReadRecordsRequest(...))。参见 references/health-connect.md。3. Google Play Billing:使用insertRecords(...);其BillingClient.newBuilder(context).setListener(purchasesUpdatedListener).enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()).build()必须实际重新连接,例如使用指数退避或在下一次请求时重连,而不是只记录日志;还要实现BillingClientStateListener.onBillingServiceDisconnected()、queryProductDetailsAsync和launchBillingFlow(activity, params)。可以显示占位价格作为 fallback,但在客户端未就绪或没有 Activity 时购买必然失败——应删除 mock 购买代码,而不是将其保留为acknowledgePurchase分支。参见 references/in-app-billing.md。4. Bluetooth LE:使用else→BluetoothManager,并提供具体的BluetoothLeScanner.startScan(filters, settings, scanCallback);还要提供具体的ScanCallback(BluetoothGattCallback、onConnectionStateChange、onServicesDiscovered),解析 iOS 代码读取的 GATT characteristic。Manifest:onCharacteristicChanged(除非扫描结果用于推导位置,否则使用BLUETOOTH_SCAN)和android:usesPermissionFlags="neverForLocation",两者都必须在运行时请求;旧式BLUETOOTH_CONNECT/BLUETOOTH以及仅用于扫描的BLUETOOTH_ADMIN应使用ACCESS_FINE_LOCATION加以限制。参见 references/bluetooth-ble.md。5. 位置:使用android:maxSdkVersion="30",配合LocationServices.getFusedLocationProviderClient(context)和LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMillis)(LocationCallback/requestLocationUpdates)。当跟踪必须在 UI 离开屏幕后继续时(iOSremoveLocationUpdates/allowsBackgroundLocationUpdates),添加一个调用UIBackgroundModes: location并显示持续通知的startForeground,在 Manifest 中声明Service,同时添加android:foregroundServiceType="location"和FOREGROUND_SERVICE。除非某条代码路径在没有可见 UI 和前台服务的情况下读取位置,否则不要声明FOREGROUND_SERVICE_LOCATION;绝不能声明迁移代码未使用的权限。参见 references/location-fusedprovider.md。6. WorkManager:使用ACCESS_BACKGROUND_LOCATION,通过CoroutineWorker调度,并映射 iOS 任务的频率和约束。参见 references/background-tasks-workmanager.md。WorkManager.getInstance(context).enqueueUniquePeriodicWork(..., ExistingPeriodicWorkPolicy.KEEP, PeriodicWorkRequestBuilder<...>(...).setConstraints(...).build())
Runtime Permission Invariants
运行时权限不变量
The permission layer is the most frequently omitted part of an iOS→Android
migration, because a manifest-only port compiles cleanly and fails only at
runtime. The full pattern --- a state hook, call-site
guards, Health Connect's contract, two-step background location, and a
verification checklist --- is in references/permissions-runtime.md. Read it
before writing permission code.
rememberPermissionRequest[!CAUTION] Caution: The runtime prompt MUST be the real Android system dialog, launched throughfrom the user action that needs the permission, and a screen MUST still render its content when a permission is not granted. These shapes are a failed migration : * ❌ A utility object of staticrememberLauncherForActivityResulthelpers. Checking is not requesting. * ❌ A permission helper or launcher that is defined or imported but never invoked from a screen. * ❌hasXPermission(). Permission state may disable a control or populate an empty state; it must never replace the screen.if (granted) ScreenContent() else PermissionScreen()
- Point of use : request each dangerous permission from the action that needs it --- e.g. the control that starts location tracking → fine/coarse location; the control that scans for BLE devices → +
BLUETOOTH_SCAN; the screen or sheet that opens the camera →BLUETOOTH_CONNECT, before binding CameraX (the most commonly missed request); app entry →CAMERAon API 33+ (from aPOST_NOTIFICATIONS, without gating content).LaunchedEffect - Health Connect uses , not
PermissionController.createRequestPermissionResultContract(). The action that reads health data must first callRequestMultiplePermissions()and launch the request if anything is missing. Fall back to sample data only after denial or when the SDK is unavailable --- never instead of requesting.permissionController.getGrantedPermissions() - Background location is a second, separate request after foreground location is granted, and only if a code path needs it.
- If the source app has its own explanatory permission UI, port it as a non-blocking banner, card, or empty state that calls the request action.
- A declared dangerous permission with no runtime request reached from a screen is a failed migration (verified in the Step 10 Pre-Completion Checklist).
权限层是 iOS→Android 迁移中最常被遗漏的部分,因为仅移植 Manifest 虽然能够干净编译,却只会在运行时失败。完整模式—— 状态 hook、调用点 guard、Health Connect contract、分两步进行的后台定位,以及验证检查清单——位于 references/permissions-runtime.md 中。编写权限代码前必须阅读该文档。
rememberPermissionRequest[!CAUTION] 注意:运行时提示必须是由启动的真实 Android 系统对话框,并且必须从需要权限的用户操作触发。未授予权限时,屏幕仍必须渲染其内容。 以下形式均属于失败迁移:* ❌ 仅包含静态rememberLauncherForActivityResulthelper 的工具对象。检查权限不等于请求权限。* ❌ 定义或导入 permission helper/launcher,却从未在屏幕中调用。* ❌hasXPermission()。权限状态可以禁用控件或填充空状态,但绝不能替换整个屏幕。if (granted) ScreenContent() else PermissionScreen()
- 使用点:从需要权限的操作发起每项危险权限请求——例如启动位置跟踪的控件 → fine/coarse location;扫描 BLE 设备的控件 → +
BLUETOOTH_SCAN;打开相机的屏幕或 sheet →BLUETOOTH_CONNECT,并在绑定 CameraX 前请求(最常被遗漏);应用入口 → API 33+ 上的CAMERA(通过POST_NOTIFICATIONS发起,但不以此控制内容显示)。LaunchedEffect - Health Connect 使用 ,而不是
PermissionController.createRequestPermissionResultContract()。读取健康数据的操作必须先调用RequestMultiplePermissions(),并在缺少权限时启动请求。只有在拒绝权限或 SDK 不可用时才能回退到示例数据,绝不能以示例数据代替权限请求。permissionController.getGrantedPermissions() - 后台位置是在授予前台位置权限之后发起的第二次独立请求,并且仅在确有代码路径需要时执行。
- 如果源应用具有自己的权限说明 UI,应将其移植为非阻塞式 banner、card 或空状态,并提供请求操作入口。
- 在 中声明了危险权限,却没有任何从屏幕可达的运行时请求,属于失败迁移,必须在步骤 10 的完成前检查清单中验证。
AndroidManifest.xml
Step 10: Build Verification, Test Porting, Quality Triage & Walkthrough Generation
步骤 10:构建验证、测试移植、质量分流与迁移说明生成
Verify that the migrated Android application is fully functional, tested, and
documented.
- INCREMENTAL LAYER COMPILATION & VERTICAL SLICING GATES :
- To prevent late-stage compilation cascades across large multi-file migrations, adhere to incremental compilation gates:
- Data & Domain Gate : After implementing domain models, Room entities, DAOs, and repositories, execute to verify the foundational data layer compiles cleanly before touching the UI.
./gradlew compileDebugKotlin - Vertical Feature Slicing for UI : Author UI feature-by-feature (➡️
ViewModel➡️Screen Composable). Before implementing a screen, inspect the correspondingRoutestate data class and domain models to ensure 100% property name and type fidelity.ViewModel - Per-Slice Verification : Run after completing each feature slice (or every 2 screens). Catching a property mismatch or syntax error immediately takes seconds and guarantees a clean final build.
./gradlew compileDebugKotlin
- Data & Domain Gate : After implementing domain models, Room entities, DAOs, and repositories, execute
- At the conclusion of migration, execute and
./gradlew :app:assembleDebug. Both MUST exit 0../gradlew :app:testDebugUnitTest
- To prevent late-stage compilation cascades across large multi-file migrations, adhere to incremental compilation gates:
- Pre-Completion Checklist (run every item before finishing; each is a
search, not a recollection) :
- Debugging stubs restored : anything you stubbed, moved or commented out to isolate a failure (e.g. a minimal ) is restored;
setContent { Text("test") }hosts the real theme and navigation graph; no temporary directories or placeholder composables remain.MainActivity.kt - Permissions : every permission helper has a call site outside its own definition, and every dangerous permission in (e.g.
AndroidManifest.xml, location, Bluetooth, notifications, Health Connect) appears in a runtime request reached from a screen.CAMERA - Strings : search UI and notification code for ,
Text(",text = ",title = ",label = ",contentDescription = "/setContentTitle(", and string templates containingsetContentText("in UI files; move every user-facing hit into$per Step 8.strings.xml - Platform managers: no demo/sample-data loader is called unconditionally (Step 9 contract); every hardware/SDK path calls the real Android API.
- Database : if is used, schema parity is proven per Step 6; no Room query runs on the main thread.
createFromAsset() - Re-run and
./gradlew :app:assembleDebug; both exit 0../gradlew :app:testDebugUnitTest
- Debugging stubs restored : anything you stubbed, moved or commented out to isolate a failure (e.g. a minimal
- Turn Completion : Do NOT end your turn or output a waiting message after starting a background build; keep working or wait for it to finish.
- Port XCTest unit tests to JUnit5 / MockK, and XCUITest journeys to Compose UI tests using references/testing-unit-and-compose.md.
- If the iOS project automates screenshots (fastlane ), port it using references/screenshots-screengrab.md.
snapshot - Prioritized Quality Gate & Refinement Triage : Follow this strict 3-tier feedback protocol when validating:
- Priority #1: Stability (Crashes): Fix all unhandled exceptions, KSP annotation crashes, or runtime crashes immediately. Iterate until the app is stable.
- Priority #2: Core Feature Parity : Check that all CUJs and top-level navigation tabs in are implemented with complete, functional Material 3 screens across the full navigation graph. Trigger at most a single (one-time) refinement loop per feature.
feature_specification.md - Priority #3: Critical UI Defects : Resolve obvious layout breakage (padding, clipping, margins), jarring unstyled default colors, missing drawables, and Edge-to-Edge compliance. Ignore minor cosmetic or typography nitpicks to avoid thrashing.
- Generate Migration Walkthrough : Write documenting all transformed components, verification outcomes, and architectural decisions. Every "implemented X" claim MUST name the file where X is actually used (not just defined) --- e.g. the screen/button that invokes a permission request. If you cannot point to a call site, the feature is not implemented; go back and wire it.
.migration/migration_walkthrough.md
验证迁移后的 Android 应用功能完整、测试充分且文档完善。
- 增量分层编译与垂直切片关卡:
- 为防止大型多文件迁移在后期产生连锁编译错误,必须遵守增量编译关卡:
- 数据与领域关卡:实现领域模型、Room entity、DAO 和 repository 后,执行 ,确认基础数据层能够在 UI 开发前干净编译。
./gradlew compileDebugKotlin - UI 垂直功能切片:逐个功能编写 UI(➡️
ViewModel➡️Screen Composable)。实现屏幕之前,检查对应的Route状态 data class 和领域模型,确保属性名称与类型完全一致。ViewModel - 逐切片验证:每完成一个功能切片(或每两个屏幕)后,运行 。立即捕获属性不匹配或语法错误只需数秒,并能保证最终构建干净。
./gradlew compileDebugKotlin
- 数据与领域关卡:实现领域模型、Room entity、DAO 和 repository 后,执行
- 迁移结束时,执行 和
./gradlew :app:assembleDebug。两者都必须以状态码 0 退出。./gradlew :app:testDebugUnitTest
- 为防止大型多文件迁移在后期产生连锁编译错误,必须遵守增量编译关卡:
- 完成前检查清单(结束前逐项执行;每项都应执行搜索,而不是凭记忆确认):
- 恢复调试 stub:为隔离故障而 stub、移动或注释的任何内容,例如最小的 ,都必须恢复;
setContent { Text("test") }必须承载真实主题和导航图;不得残留临时目录或占位 composable。MainActivity.kt - 权限:每个 permission helper 都必须在自身定义之外存在调用点;中的每项危险权限,例如
AndroidManifest.xml、位置、Bluetooth、通知、Health Connect,都必须出现在从屏幕可达的运行时请求中。CAMERA - 字符串:在 UI 和通知代码中搜索 、
Text("、text = "、title = "、label = "、contentDescription = "/setContentTitle(",以及 UI 文件中包含setContentText("的字符串模板;按照步骤 8 将每个面向用户的命中项移入$。strings.xml - 平台 manager:不得无条件调用 demo/sample-data loader(步骤 9 契约);每条硬件/SDK 路径都必须调用真实的 Android API。
- 数据库:如果使用 ,必须按照步骤 6 证明 schema 一致;任何 Room 查询都不能在主线程运行。
createFromAsset() - 重新运行 和
./gradlew :app:assembleDebug;两者都以状态码 0 退出。./gradlew :app:testDebugUnitTest
- 恢复调试 stub:为隔离故障而 stub、移动或注释的任何内容,例如最小的
- 回合完成:启动后台构建后,不要结束回合或输出等待消息;应继续工作或等待构建完成。
- 使用 references/testing-unit-and-compose.md 将 XCTest 单元测试移植到 JUnit5/MockK,并将 XCUITest 用户流程移植到 Compose UI 测试。
- 如果 iOS 项目通过 fastlane 自动执行截图测试,应使用 references/screenshots-screengrab.md 进行移植。
snapshot - 优先级质量关卡与改进分流:验证时遵循严格的 3 层反馈协议:
- 优先级 #1:稳定性(崩溃):立即修复所有未处理异常、KSP 注解崩溃或运行时崩溃。持续迭代,直到应用稳定。
- 优先级 #2:核心功能一致性:检查 中的所有 CUJ 和顶层导航标签是否都已在完整导航图中实现为功能完整、可用的 Material 3 屏幕。每个功能最多触发**一次(单次)**改进循环。
feature_specification.md - 优先级 #3:严重 UI 缺陷:解决明显的布局破坏(padding、裁剪、margin)、突兀的默认样式、缺失的 drawable,以及 Edge-to-Edge 合规问题。忽略轻微的外观或排版细节问题,避免反复折腾。
- 生成迁移说明:编写 ,记录所有已转换组件、验证结果和架构决策。每项“已实现 X”的声明都必须指出实际使用 X 的文件,而不只是定义它的文件——例如实际调用权限请求的屏幕/按钮。如果无法指出调用点,则该功能尚未实现;必须返回并完成接线。
.migration/migration_walkthrough.md
Antipatterns
反模式
DO
应该做
- DO run the automated project audit before writing any code.
- DO preserve the existing ,
namespace, and root package structure when migrating into an existing Android project shell---only generate wholly new project/Gradle files if none exist to start, and only update Gradle configuration (applicationId,app/build.gradle.kts) to add libraries/plugins required for functionality being ported.libs.versions.toml - DO scale your package architecture contextually: compact files for small single-feature utilities (< 1,000 LOC); full multi-package architecture for complex multi-journey apps (> 1,000 LOC / 5+ screens), with every screen of the source app reachable in the graph.
NavHost - DO declare in the Android 14+ permission for every iOS
AndroidManifest.xmlprivacy key the app actually uses (see the mapping table in references/permissions-runtime.md).Info.plist - DO ensure all added permissions are requested at runtime according to Jetpack Compose best practices using (and Health Connect permission request contracts) rather than only declaring them in the manifest.
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) - DO keep UI strings in and colors in a Light + Dark Material 3 theme, migrate relational data to Room (
res/values/strings.xml,@Entity,@DaoexposingRoomDatabase), and useFlowfor key-value settings.DataStore<Preferences> - DO produce a formal capturing non-obvious logic and data flows.
feature_specification.md - DO verify the complete migration with a consolidated compile and test check (and
./gradlew assembleDebug) at the conclusion of code generation../gradlew testDebugUnitTest - DO load only the specific reference files flagged during the initial audit.
- DO use Jetpack Compose, Material Design 3, and for all UI screens, collecting state via
enableEdgeToEdge()and using explicitcollectAsStateWithLifecycle()inkey = { ... }items.LazyColumn - DO isolate all secrets and API keys in .
local.properties - DO generate functions for every top-level composable screen.
@Preview
- 应该在编写任何代码之前执行自动化项目审计。
- 应该在迁移到现有 Android 项目骨架时保留现有 、
namespace和根包结构——仅在没有任何现有项目/Gradle 文件时生成全新的项目和 Gradle 文件,并且只更新 Gradle 配置(applicationId、app/build.gradle.kts)以添加功能移植所需的库/插件。libs.versions.toml - 应该根据上下文调整包架构:小巧的单功能工具使用紧凑文件(< 1,000 LOC);复杂的多流程应用使用完整多包架构(> 1,000 LOC/5 个以上屏幕),并确保源应用的每个屏幕都可从 图中到达。
NavHost - 应该在 中为应用实际使用的每个 iOS
AndroidManifest.xml隐私键声明对应的 Android 14+ 权限,参见 references/permissions-runtime.md 中的映射表。Info.plist - 应该按照 Jetpack Compose 最佳实践,使用 (以及 Health Connect 权限请求 contract)在运行时请求所有新增权限,而不是仅在 Manifest 中声明。
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) - 应该将 UI 字符串保留在 中,将颜色放入 Light + Dark Material 3 主题,将关系数据迁移到 Room(
res/values/strings.xml、@Entity、暴露@Dao的Flow),并使用RoomDatabase保存键值设置。DataStore<Preferences> - 应该生成正式的 ,记录不明显逻辑和数据流。
feature_specification.md - 应该在代码生成结束时,通过合并的编译与测试检查(和
./gradlew assembleDebug)验证完整迁移。./gradlew testDebugUnitTest - 应该只加载初始审计标记出的特定参考文件。
- 应该为所有 UI 屏幕使用 Jetpack Compose、Material Design 3 和 ,通过
enableEdgeToEdge()收集状态,并在collectAsStateWithLifecycle()项中使用明确的LazyColumn。key = { ... } - 应该将所有密钥和 API Key 隔离在 中。
local.properties - 应该为每个顶层 composable 屏幕生成 函数。
@Preview
DON'T
不应该做
- DON'T claim migration success without real, verified CLI execution output showing exit code 0.
- DON'T overwrite existing , root
settings.gradle.kts, orbuild.gradle.ktsfrom scratch or change the rootapp/build.gradle.kts/package name when migrating into an existing Android project shell.namespace - DON'T collapse a complex multi-screen application into a single monolithic file or use barebones test-tag stub buttons instead of functional Material 3 screens.
MainActivity.kt - DON'T declare permissions in without also implementing runtime permission requests (
AndroidManifest.xml) in the UI layer.rememberLauncherForActivityResult - DON'T enter infinite refinement loops for minor cosmetic or typography differences.
- DON'T load all supplemental reference files simultaneously into the agent's context.
- DON'T access files in without first reading and following the primary orchestration protocol in
references/.SKILL.md - DON'T translate Swift code line-by-line; translate concepts, architectural boundaries, and behaviors.
- DON'T use legacy Android XML Views, , or
findViewByIdin new migrations.AsyncTask - DON'T fail silently on unsupported or proprietary iOS APIs.
- 不应该在没有真实、已验证且显示状态码 0 的 CLI 执行输出时宣称迁移成功。
- 不应该从头覆盖现有 、根
settings.gradle.kts或build.gradle.kts,也不应该在迁移到现有 Android 项目骨架时更改根app/build.gradle.kts/包名。namespace - 不应该将复杂的多屏幕应用折叠成单个巨型 文件,也不应该使用只有测试标签的简陋 stub 按钮代替功能完整的 Material 3 屏幕。
MainActivity.kt - 不应该只在 中声明权限,却不在 UI 层实现运行时权限请求(
AndroidManifest.xml)。rememberLauncherForActivityResult - 不应该因轻微的外观或排版差异进入无限改进循环。
- 不应该一次性将所有补充参考文件加载到 agent 的上下文中。
- 不应该在未阅读并遵循 中主要编排协议的情况下访问
SKILL.md中的文件。references/ - 不应该逐行翻译 Swift 代码;应转换其概念、架构边界和行为。
- 不应该在新迁移中使用旧式 Android XML Views、或
findViewById。AsyncTask - 不应该对不支持或专有的 iOS API 静默失败。
NEVER
绝不允许
- NEVER finalize a migration without verifying that exits 0.
./gradlew assembleDebug - NEVER exit a turn or emit messages like "Waiting for tests/build to complete..." without authoring the requested Kotlin implementation diff.
- NEVER hardcode API keys, secrets, or tokens in source code or version control.
- NEVER leave empty placeholder functions or comments in production Kotlin source files.
TODO - NEVER ignore iOS permissions during the initial audit phase.
Info.plist
- 绝不在未验证 以状态码 0 退出的情况下结束迁移。
./gradlew assembleDebug - 绝不在未编写所请求 Kotlin 实现 diff 的情况下结束回合,或输出“正在等待测试/构建完成……”之类的消息。
- 绝不在源代码或版本控制中硬编码 API Key、密钥或 token。
- 绝不在生产 Kotlin 源文件中留下空占位函数或 注释。
TODO - 绝不在初始审计阶段忽略 iOS 权限。
Info.plist