ios-to-android

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
This 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
references/
based on the specific subsystems detected in the source codebase.
本 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
    references/
    for each subsystem present in the source codebase:
    1. Architecture & State : Inspect references/architecture-and-viewmodels.md and references/state-and-reactive-flows.md.
    2. Screen Layouts & Declarative UI : Inspect references/ui-layout-swiftui-to-compose.md.
    3. Navigation : Inspect references/navigation-compose.md.
    4. Database & Entities : Inspect references/database-coredata-to-room.md.
    5. Preferences & Settings : Inspect references/preferences-datastore.md.
    6. Runtime Permissions : Inspect references/permissions-runtime.md.
    7. Health & Fitness : Inspect references/health-connect.md.
    8. In-App Billing & Store : Inspect references/in-app-billing.md.
    9. Bluetooth LE Sensors : Inspect references/bluetooth-ble.md.
    10. Location & GPS Tracking : Inspect references/location-fusedprovider.md.
    11. Background Tasks : Inspect references/background-tasks-workmanager.md.
[!IMPORTANT] Important: This gate is mandatory. Reading
SKILL.md
alone 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.
You MUST record the list of reference guides you actually opened in
.migration/migration_walkthrough.md
under a
## Reference Guides Consulted
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.
  • 触发条件:用户要求从头到尾迁移整个 iOS 应用,或者目标目录为空/仅包含一个干净的起始骨架。
  • 工作流:依次执行完整的 10 步方法(步骤 1 至步骤 10),将应用拆分为多包架构、建立构建配置、移植所有子系统,并通过最终合并后的构建关卡进行验证。
  • 强制迁移前子系统检查关卡:在为检测到的任何 iOS 领域能力实现 Android 代码之前,对于源代码库中存在的每个子系统,你必须明确查看并检查
    references/
    中对应的参考指南:
    1. 架构与状态:检查 references/architecture-and-viewmodels.md 和 references/state-and-reactive-flows.md。
    2. 屏幕布局与声明式 UI:检查 references/ui-layout-swiftui-to-compose.md。
    3. 导航:检查 references/navigation-compose.md。
    4. 数据库与实体:检查 references/database-coredata-to-room.md。
    5. 偏好与设置:检查 references/preferences-datastore.md。
    6. 运行时权限:检查 references/permissions-runtime.md。
    7. 健康与健身:检查 references/health-connect.md。
    8. 应用内计费与商店:检查 references/in-app-billing.md。
    9. Bluetooth LE 传感器:检查 references/bluetooth-ble.md。
    10. 位置与 GPS 跟踪:检查 references/location-fusedprovider.md。
    11. 后台任务:检查 references/background-tasks-workmanager.md。
[!IMPORTANT] **重要:**此关卡是强制性的。 仅阅读
SKILL.md
不足以完成迁移——本根文档只是索引和一组不变量;真正的 API 级实现模式位于参考指南中。跳过它们是 mock-stub manager、缺失运行时权限,以及虽能干净编译却在评审时失败的非惯用布局的最常见原因。
你必须在
.migration/migration_walkthrough.md
的
## Reference Guides Consulted
标题下记录实际打开的参考指南列表。如果源应用中存在某个子系统,但其指南未出现在该列表中,则迁移尚未完成——必须返回并阅读对应指南,然后才能结束。

Mode 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 :
    1. Target Codebase Convention Discovery: Inspect the target Android project to discover and adopt established architecture, package structure, dependency injection, and state patterns.
    2. Surgical Subsystem Routing : Jump directly to the relevant supplemental reference guide in
      references/
      for the requested capability.
    3. Scoped Migration & Integration: Implement the subsystem matching the discovered target conventions and wire it to replace any existing Fakes or stubs.
    4. Targeted Build & Test Verification : Verify
      ./gradlew assembleDebug
      or run specific unit tests without mutating unrelated modules.
  • Anti-Premature-Exit & Execution Liveness Mandate :
    • NEVER exit or yield prematurely on background tasks : If a build or test command (
      ./gradlew assembleDebug
      ,
      ./gradlew test
      ) 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 (
      WaitMsBeforeAsync: 10000
      ) or monitor the task to completion.
    • A task is NEVER finished without the implementation diff : You must author or update the target Kotlin source files (
      write_to_file
      ,
      replace_file_content
      ) replacing mock/stub implementations with real Android Jetpack/platform APIs before concluding.

  • 触发条件:用户要求将特定子系统、功能、屏幕或能力(例如 CoreData 到 Room、HealthKit 到 Health Connect、StoreKit 到 Play Billing、BLE 或某个具体屏幕)迁移到现有 Android 项目中。
  • 绕开宏观开销:不要对整个 iOS 仓库执行完整的 10 步审计,也不要生成完整的
    .migration/feature_specification.md
    。
  • 执行四阶段微工作流:
    1. 目标代码库约定发现:检查目标 Android 项目,发现并采用其既有架构、包结构、依赖注入和状态模式。
    2. 精准子系统路由:直接进入
      references/
      中与所请求能力对应的补充参考指南。
    3. 范围受限的迁移与集成:按照发现的目标约定实现子系统,并将其接入以替换现有的 Fakes 或 stubs。
    4. 针对性构建与测试验证:执行
      ./gradlew assembleDebug
      或运行特定单元测试,且不得修改无关模块。
  • 禁止提前退出与执行活性要求:
    • 绝不提前退出或在后台任务上无谓暂停:如果构建或测试命令(
      ./gradlew assembleDebug
      、
      ./gradlew test
      )异步运行,在没有待处理工具调用的情况下,不要输出“正在等待测试完成……”之类的被动等待消息。在非交互式运行中,如果在没有待处理工具调用的情况下结束回合,任务会在构建完成前终止。你应当同步等待(
      WaitMsBeforeAsync: 10000
      )或持续监控任务直至完成。
    • 没有实现 diff,任务绝不视为完成:结束前,你必须编写或更新目标 Kotlin 源文件(
      write_to_file
      、
      replace_file_content
      ),以真实的 Android Jetpack/平台 API 替换 mock/stub 实现。

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
app/src/main/java/
and
gradle/libs.versions.toml
before creating or modifying files. Adopt the target project's established conventions across these 5 dimensions:
  1. Package Organization :
    • Layer-based (
      data/
      ,
      domain/
      ,
      ui/
      ) vs. Feature-based (
      feature/home/
      ,
      feature/catalog/
      ). Place new files into the existing package hierarchy rather than inventing an incompatible tree.
  2. Dependency Injection & Service Locator :
    • Discover how dependencies are provided: Hilt (
      @Inject
      ,
      @HiltViewModel
      ,
      @InstallIn
      ), Koin , or manual AppContainer / Service Locator pattern.
    • Do NOT introduce a foreign DI framework . If the target app uses manual DI or an
      AppContainer
      , provide clean constructor injections that plug directly into that container. If it uses Hilt, provide Hilt
      @Module
      and
      @Provides
      bindings.
  3. State Management & Concurrency :
    • Observe how ViewModels expose UI state: unified
      StateFlow<UiState>
      data classes, individual StateFlows, or Compose
      MutableState
      .
    • Observe how Coroutine dispatchers are provided (e.g., injected
      @IoDispatcher
      vs
      Dispatchers.IO
      ).
  4. Design System & UI Components :
    • Inspect
      ui/theme/
      and common component directories. If the codebase defines custom composable wrappers (e.g.
      AppButton
      ,
      AppCard
      , custom typography tokens), reuse them rather than falling back to generic default primitives.
  5. Version Catalog & Dependencies :
    • Inspect
      gradle/libs.versions.toml
      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.

在现有 Android 代码库中执行子组件迁移时,你必须在创建或修改文件之前,检查
app/src/main/java/
中的 2--3 个现有文件以及
gradle/libs.versions.toml
。你必须在这 5 个维度上采用目标项目的既有约定:
  1. 包组织方式:
    • 基于层级(
      data/
      、
      domain/
      、
      ui/
      )还是基于功能(
      feature/home/
      、
      feature/catalog/
      )。将新文件放入现有包层级,而不是创建不兼容的目录树。
  2. 依赖注入与服务定位器:
    • 发现依赖的提供方式:Hilt(
      @Inject
      、
      @HiltViewModel
      、
      @InstallIn
      )、Koin,或手动 AppContainer/Service Locator 模式。
    • 不要引入外部的 DI 框架。如果目标应用使用手动 DI 或
      AppContainer
      ,请提供可直接接入该容器的干净构造函数注入。如果使用 Hilt,则提供 Hilt
      @Module
      和
      @Provides
      绑定。
  3. 状态管理与并发:
    • 观察 ViewModel 如何暴露 UI 状态:统一的
      StateFlow<UiState>
      data class、独立的 StateFlow,或 Compose
      MutableState
      。
    • 观察 Coroutine dispatcher 的提供方式,例如注入
      @IoDispatcher
      还是直接使用
      Dispatchers.IO
      。
  4. 设计系统与 UI 组件:
    • 检查
      ui/theme/
      和公共组件目录。如果代码库定义了自定义 composable 包装器,例如
      AppButton
      、
      AppCard
      或自定义排版 token,应复用它们,而不是退回到通用默认 primitive。
  5. 版本目录与依赖项:
    • 添加依赖项之前检查
      gradle/libs.versions.toml
      。如果某个库系列(例如 Room、Coroutines、Serialization)已经存在,应复用项目现有版本和 alias,而不是添加重复项。

Summary of the 10-Step Migration Methodology (Mode A)

10 步迁移方法摘要(模式 A)

  1. Deep Source Audit, Domain Discovery & Migration Brief
  2. Subsystem & Capability Decomposition
  3. Formulate and Approve Phased Migration Plan
  4. Project Infrastructure, Gradle & DI Initialization (Mandatory Build Gate 1)
  5. Resource Catalog & Localization Migration
  6. Local Persistence & Storage Migration (Mandatory Build Gate 2)
  7. Core Architecture, Concurrency, State Hoisting & Secrets Handling
  8. Declarative UI & Navigation Porting to Jetpack Compose (Mandatory Build Gate 3)
  9. Hardware, Platform Services & Background Subsystems
  10. Build Verification, Test Porting, Quality Triage & Walkthrough Generation (Mandatory Build Gate 4)

  1. 深入源审计、领域发现与迁移简报
  2. 子系统与能力拆分
  3. 制定并确认分阶段迁移计划
  4. 项目基础设施、Gradle 与 DI 初始化(强制构建关卡 1)
  5. 资源目录与本地化迁移
  6. 本地持久化与存储迁移(强制构建关卡 2)
  7. 核心架构、并发、状态提升与密钥处理
  8. 向 Jetpack Compose 移植声明式 UI 与导航(强制构建关卡 3)
  9. 硬件、平台服务与后台子系统
  10. 构建验证、测试移植、质量分流与迁移说明生成(强制构建关卡 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
    find . -maxdepth 3 -type d
    and inventory dependencies via
    Podfile
    ,
    Package.swift
    , or
    Cartfile
    .
  • Generate Migration Brief : Produce a formal
    feature_specification.md
    in
    .migration/
    summarizing all features, entry/exit points, data flows, and Android target equivalents.
  • 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/
    中生成正式的
    feature_specification.md
    ,概述所有功能、入口与出口、数据流以及 Android 目标对应物。
  • 查阅 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 PatternSupplemental Reference GuideAndroid Target Architecture
import SwiftUI
/
List
/
VStack
references/ui-layout-swiftui-to-compose.mdJetpack Compose (LazyColumn, Row, Column, Box)
import CoreData
/
.xcdatamodeld
references/database-coredata-to-room.mdJetpack Room, SQLite, KSP
import CoreLocation
/
NSLocation*
references/location-fusedprovider.mdFusedLocationProviderClient / LocationManager
import StoreKit
references/in-app-billing.mdGoogle Play Billing Library 8
import HealthKit
/
HKHealthStore
references/health-connect.mdJetpack Health Connect
import CoreBluetooth
/
CBCentralManager
references/bluetooth-ble.mdAndroid BLE GATT & Scanner
import AVFoundation
/
AVCaptureSession
references/camera-camerax.mdJetpack CameraX (PreviewView, ImageAnalysis)
import UserNotifications
/ APNs
references/push-notifications-fcm.mdNotificationManager & FCM
BGTaskScheduler
/
BGAppRefreshTask
references/background-tasks-workmanager.mdAndroid WorkManager (CoroutineWorker)
UserDefaults
/
@AppStorage
references/preferences-datastore.mdJetpack Preferences DataStore
NavigationStack
/
NavigationView
references/navigation-compose.mdNavigation Compose with Type-Safe Routing
withAnimation
/
.animation(
references/ui-animations.mdJetpack Compose Animation APIs
import XCTest
/
XCUITest
references/testing-unit-and-compose.mdJUnit5, MockK, ComposeTestRule
fastlane/Snapfile
/
snapshot(
references/screenshots-screengrab.mdFastlane Screengrab, UI Automator
检测到的 iOS 标识/代码模式补充参考指南Android 目标架构
import SwiftUI
/
List
/
VStack
references/ui-layout-swiftui-to-compose.mdJetpack Compose(LazyColumn、Row、Column、Box)
import CoreData
/
.xcdatamodeld
references/database-coredata-to-room.mdJetpack Room、SQLite、KSP
import CoreLocation
/
NSLocation*
references/location-fusedprovider.mdFusedLocationProviderClient / LocationManager
import StoreKit
references/in-app-billing.mdGoogle Play Billing Library 8
import HealthKit
/
HKHealthStore
references/health-connect.mdJetpack Health Connect
import CoreBluetooth
/
CBCentralManager
references/bluetooth-ble.mdAndroid BLE GATT 与 Scanner
import AVFoundation
/
AVCaptureSession
references/camera-camerax.mdJetpack CameraX(PreviewView、ImageAnalysis)
import UserNotifications
/ APNs
references/push-notifications-fcm.mdNotificationManager 与 FCM
BGTaskScheduler
/
BGAppRefreshTask
references/background-tasks-workmanager.mdAndroid WorkManager(CoroutineWorker)
UserDefaults
/
@AppStorage
references/preferences-datastore.mdJetpack Preferences DataStore
NavigationStack
/
NavigationView
references/navigation-compose.mdNavigation Compose 与类型安全路由
withAnimation
/
.animation(
references/ui-animations.mdJetpack Compose Animation APIs
import XCTest
/
XCUITest
references/testing-unit-and-compose.mdJUnit5、MockK、ComposeTestRule
fastlane/Snapfile
/
snapshot(
references/screenshots-screengrab.mdFastlane 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 / CapabilityAndroid Runtime MechanismDedicated Android Contract / API
Standard Runtime Permissions (
Camera
,
Location
,
Bluetooth
)
Activity Result Launcher
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
HealthKit (
HKHealthStore.requestAuthorization
)
Health Connect Permission Contract
rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract())
Photo Library (
PHPickerViewController
)
Activity Result Photo Picker
rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia())
Document Picker (
UIDocumentPickerViewController
)
Storage Access Framework
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument())
In-App Purchases / Subscriptions (
StoreKit
)
Play Billing Flow
BillingClient.launchBillingFlow(activity, billingFlowParams)
Android 14+ Foreground ServicesManifest Service Declaration`<service android:foregroundServiceType="health
[!IMPORTANT] Important: Android 14+ (API 34+) Manifest & Foreground Service Rules : 1. Foreground Service Types : Any
<service>
tag in
AndroidManifest.xml
that runs in the foreground MUST specify
android:foregroundServiceType
matching the exact permissions and functionality used (e.g.
health
,
location
,
dataSync
,
camera
,
connectedDevice
). Omitting this attribute will trigger a runtime
SecurityException
on Android 14+. 2.
Info.plist
HealthKit Mapping (
NSHealthShareUsageDescription
/
NSHealthUpdateUsageDescription
)
: Always map iOS HealthKit privacy keys in
AndroidManifest.xml
to Android 14+ Health Connect permissions (
android.permission.health.READ_STEPS
,
android.permission.health.READ_HEART_RATE
,
android.permission.health.READ_ACTIVE_CALORIES_BURNED
, etc.) alongside
<queries><package android:name="com.google.android.apps.healthdata" /></queries>
.
在 Android 上,不同系统能力需要采用不同的运行时调用机制。移植 iOS 系统对话框和授权流程时,你必须使用专用的 Android contract,而不是通用权限请求:
iOS 框架/能力Android 运行时机制专用 Android Contract/API
标准运行时权限(
Camera
、
Location
、
Bluetooth
)
Activity Result Launcher
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
HealthKit(
HKHealthStore.requestAuthorization
)
Health Connect Permission Contract
rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract())
照片图库(
PHPickerViewController
)
Activity Result Photo Picker
rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia())
文档选择器(
UIDocumentPickerViewController
)
Storage Access Framework
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument())
应用内购买/订阅(
StoreKit
)
Play Billing Flow
BillingClient.launchBillingFlow(activity, billingFlowParams)
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
、
connectedDevice
。在 Android 14+ 上省略此属性会触发运行时
SecurityException
。2.
Info.plist
HealthKit 映射(
NSHealthShareUsageDescription
/
NSHealthUpdateUsageDescription
)
:始终将 iOS HealthKit 隐私键映射到
AndroidManifest.xml
中 Android 14+ 的 Health Connect 权限(
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
    libs.versions.toml
    , and sequential execution milestones.
  • 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:
  1. 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.
  2. 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 (
      MainActivity.kt
      ) or substitute functional screens with barebones test-tag stubs.
    • 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/
        ).
        MainActivity.kt
        must only initialize
        enableEdgeToEdge()
        , runtime permission launchers, and the root
        NavHost
        scaffold.
      • Complete Local Persistence (
        data/local/
        &
        data/preferences/
        )
        : Implement concrete
        @Entity
        classes for all core domain tables (e.g., both the catalog entity and the user-history entity), a
        @Dao
        interface exposing
        Flow<List<T>>
        queries, and a
        RoomDatabase
        . Implement asynchronous
        DataStore<Preferences>
        for user settings and authentication tokens.
      • Extracted Android Resources (
        res/values/strings.xml
        &
        ui/theme/Theme.kt
        )
        : Extract user-facing strings into
        res/values/strings.xml
        and define both Light and Dark Material 3
        ColorScheme
        s in
        Theme.kt
        .
      • Complete Navigation Graph (
        ui/navigation/NavGraph.kt
        )
        : Build a
        NavHost
        covering both top-level bottom navigation tabs (
        launchSingleTop = true
        ,
        restoreState = true
        ) AND distinct sub-flow destinations (e.g. onboarding, detail screens, full-screen task flows). Model onboarding / first-run flows as destinations inside that
        NavHost
        (choose the start destination from the persisted "onboarding complete" flag); never render them as a separate composable tree outside the
        NavHost
        that calls
        navController.navigate(...)
        before the graph has been set, which throws at runtime.
      • Runtime Permission Launchers : In addition to declaring the Android 14+ permissions for each capability the source app uses in
        AndroidManifest.xml
        , invoke
        rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
        at runtime in the Compose UI layer.
      • Feature-Complete Material 3 Screens (
        ui/screens/*.kt
        )
        : Every screen must collect state from a Jetpack
        ViewModel
        via
        collectAsStateWithLifecycle()
        (never raw
        collectAsState()
        ), render scrollable lists using
        LazyColumn
        with explicit
        key = { ... }
        parameters, and present Material 3 content showing the real domain data from the source app's models (not placeholder text), matching the functional specification.
生成 Android 源文件之前,评估 iOS 源项目的规模和复杂度,并选择合适的结构层级:
  1. 第 1 层:微型应用、单功能工具或范围受限的原型(< 1,000 LOC/1--2 个屏幕)
    • 允许合并:迁移小型、自包含的工具或单屏幕组件时,如果能够提升可读性并避免过度工程化,可以将领域模型、状态持有者与 Compose UI 合并到紧凑的包或单个内聚文件中。
  2. 第 2 层:多功能生产应用(> 1,000 LOC/5 个以上屏幕/包含多个子系统,例如 CoreData、BLE、HealthKit、Maps)
    • 强制完整架构拆分:迁移复杂、多流程应用(例如生产应用)时,你不得将整个应用折叠成单个巨型文件(
      MainActivity.kt
      ),也不得使用只有测试标签的简陋 stub 来替代功能屏幕。
    • 复杂应用强制多包执行协议:
      • 包拆分:按逻辑组织代码(
        data/local/
        、
        data/preferences/
        、
        domain/model/
        、
        ui/navigation/
        、
        ui/screens/
        、
        ui/theme/
        )。
        MainActivity.kt
        只能负责初始化
        enableEdgeToEdge()
        、运行时权限 launcher 和根级
        NavHost
        脚手架。
      • 完整的本地持久化(
        data/local/
        与
        data/preferences/
        )
        :为所有核心领域表实现具体的
        @Entity
        类,例如目录 entity 和用户历史 entity;实现暴露
        Flow<List<T>>
        查询的
        @Dao
        接口,以及
        RoomDatabase
        。使用异步
        DataStore<Preferences>
        保存用户设置和认证 token。
      • 提取 Android 资源(
        res/values/strings.xml
        与
        ui/theme/Theme.kt
        )
        :将面向用户的字符串提取到
        res/values/strings.xml
        ,并在
        Theme.kt
        中定义 Light 与 Dark Material 3
        ColorScheme
        。
      • 完整导航图(
        ui/navigation/NavGraph.kt
        )
        :构建覆盖所有顶层底部导航标签(
        launchSingleTop = true
        、
        restoreState = true
        )以及不同子流程目的地(例如 onboarding、详情屏幕、全屏任务流程)的
        NavHost
        。将 onboarding/首次运行流程建模为
        NavHost
        内的目的地,根据持久化的“onboarding complete”标志选择起始目的地;绝不要在图尚未设置时,在
        NavHost
        外部渲染单独的 composable 树并调用
        navController.navigate(...)
        ,否则会在运行时抛出异常。
      • 运行时权限 Launcher:除了在
        AndroidManifest.xml
        中声明源应用使用的每项能力所需的 Android 14+ 权限外,还必须在运行时于 Compose UI 层调用
        rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
        。
      • 功能完整的 Material 3 屏幕(
        ui/screens/*.kt
        )
        :每个屏幕都必须通过
        collectAsStateWithLifecycle()
        从 Jetpack
        ViewModel
        收集状态,绝不能使用原始
        collectAsState()
        ;使用带有明确
        key = { ... }
        参数的
        LazyColumn
        渲染可滚动列表;使用 Material 3 展示来自源应用模型的真实领域数据,而不是占位文本,并符合功能规范。

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
    ,
    app/build.gradle.kts
    , and
    MainActivity.kt
    are present):
    • DO NOT generate wholly new project files or overwrite
      settings.gradle.kts
      , root
      build.gradle.kts
      , or
      app/build.gradle.kts
      from scratch.
    • MUST PRESERVE the existing
      namespace
      ,
      applicationId
      , and root package name (e.g., keep
      MainActivity.kt
      in its existing root package and place all new sub-packages---
      data/local/
      ,
      data/preferences/
      ,
      domain/model/
      ,
      ui/navigation/
      ,
      ui/screens/
      ,
      ui/theme/
      ---under that same root package).
    • Incremental Gradle Updates Only : Modify
      app/build.gradle.kts
      and
      gradle/libs.versions.toml
      to 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.
    • Mandatory Subsystem Dependencies in
      app/build.gradle.kts
      :
      • If HealthKit (
        import HealthKit
        ) is detected: set
        minSdk = 26
        in
        defaultConfig {}
        and add
        implementation("androidx.health.connect:connect-client:1.1.0-alpha07")
        and
        implementation("com.google.guava:guava:33.0.0-android")
        to
        dependencies {}
        .
      • If StoreKit (
        import StoreKit
        ) is detected: add
        implementation("com.android.billingclient:billing-ktx:8.3.0")
        to
        dependencies {}
        .
      • If BGTaskScheduler (
        import BackgroundTasks
        ) is detected: add
        implementation("androidx.work:work-runtime-ktx:2.9.0")
        to
        dependencies {}
        .
      • If CoreLocation (
        import CoreLocation
        ) is detected: add
        implementation("com.google.android.gms:play-services-location:21.2.0")
        to
        dependencies {}
        .
  • 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
      ,
      gradle/libs.versions.toml
      ) and establish module boundaries matching iOS targets.
  • 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
      和
      gradle/libs.versions.toml
      ,在编写 manager 类之前,立即加入检测到的 iOS 能力所需的全部 Jetpack 和 Google Play 库。绝不能移除你没有添加的现有依赖项、插件或测试配置。
    • 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")
        。
  • 否则(如果从空目录开始且没有任何 Gradle 文件):
    • 使用 Kotlin DSL(
      settings.gradle.kts
      、
      build.gradle.kts
      、
      gradle/libs.versions.toml
      )初始化目标 Android 项目结构,并建立与 iOS 目标相对应的模块边界。
  • 查阅 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
    .xcassets
    into Android XML Drawables.
  • Map app icons to
    res/mipmap-anydpi-v26/ic_launcher.xml
    adaptive icons.
  • Convert
    Localizable.strings
    into
    res/values/strings.xml
    .
  • Consult references/resources-and-assets.md.
提取并将 iOS 资源目录与字符串转换为 Android 资源目录。
  • 将
    .xcassets
    中的图像资源和矢量图转换为 Android XML Drawable。
  • 将应用图标映射到
    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
    UserDefaults
    or
    @AppStorage
    is detected, replace with Preferences DataStore using references/preferences-datastore.md.
  • 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 ---
      RoomDatabase.Callback
      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
      .sqlite
      or a Realm file) and insert equivalent domain rows through your DAOs in
      onCreate()
      . This cannot fail Room's schema validation.
    • NEVER copy a bundled iOS database file (Core Data / SwiftData / GRDB / FMDB
      .sqlite
      ) verbatim into
      assets/
      and pass it to
      createFromAsset()
      unless every
      @Entity
      was deliberately written to mirror that file's exact
      Z*
      tables, columns, types, nullability and indices (see references/database-coredata-to-room.md). Room validates pre-packaged databases on first open and throws
      IllegalStateException: Pre-packaged database has an invalid schema
      , crashing the app on launch. Adding extra tables to the copied file does not fix this.
    • You usually cannot observe this crash (no device/emulator;
      assembleDebug
      still succeeds). If you do use
      createFromAsset()
      , 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.
  • Room Threading : Room throws
    IllegalStateException
    for any query on the main thread. Make DAO methods
    suspend
    or return
    Flow
    ; never call the database from a ViewModel
    init {}
    body, from composition, or inside
    runBlocking
    on the main thread --- launch the work in
    viewModelScope
    (or a repository coroutine on
    Dispatchers.IO
    ) instead. Run seeding from the
    RoomDatabase.Callback
    on a background dispatcher. Never use
    allowMainThreadQueries()
    in production code (it is acceptable only in tests).
移植数据模型、本地关系数据库和键值偏好设置。
  • 如果检测到 Core Data/SwiftData,请使用 references/database-coredata-to-room.md 将实体、类型转换器和 DAO 映射到 Room。
  • 如果检测到
    UserDefaults
    或
    @AppStorage
    ,请使用 references/preferences-datastore.md 将其替换为 Preferences DataStore。
  • 初始数据库种子数据:如果 iOS 应用附带预加载数据(示例记录、目录项、默认值),你必须在首次启动时完成播种。否则列表和详情屏幕会呈现空状态,应用在首次启动时看起来像是损坏的。
    • 默认策略——
      RoomDatabase.Callback
      播种
      :读取 iOS 种子数据(内置 JSON/plist、Swift sample-data 数组,或迁移时从 Core Data/SwiftData/GRDB/FMDB
      .sqlite
      或 Realm 文件等内置数据库提取的行),并通过 DAO 在
      onCreate()
      中插入对应的领域行。这样不会导致 Room schema 校验失败。
    • 绝不将内置 iOS 数据库文件(Core Data/SwiftData/GRDB/FMDB
      .sqlite
      )原样复制到
      assets/
      并传给
      createFromAsset()
      ,除非每个
      @Entity
      都经过刻意编写,以完整镜像该文件的
      Z*
      表、列、类型、可空性和索引,参见 references/database-coredata-to-room.md。Room 会在首次打开时校验预打包数据库,并抛出
      IllegalStateException: Pre-packaged database has an invalid schema
      ,导致应用启动崩溃。向复制文件添加额外表并不能解决问题。
    • 你通常无法观察到该崩溃(没有设备/模拟器;
      assembleDebug
      仍会成功)。如果确实使用
      createFromAsset()
      ,则必须在结束前按照 references/database-coredata-to-room.md 第 0 节“选择播种策略后再编写实体”中的无设备验证方法,从静态角度证明 schema 完全一致。
  • Room 线程处理:Room 会在主线程执行任何查询时抛出
    IllegalStateException
    。将 DAO 方法设为
    suspend
    或返回
    Flow
    ;绝不能从 ViewModel 的
    init {}
    、composition 内部或主线程上的
    runBlocking
    中调用数据库——应在
    viewModelScope
    中启动工作,或在 repository coroutine 中通过
    Dispatchers.IO
    执行。播种应从
    RoomDatabase.Callback
    在后台 dispatcher 上运行。绝不要在生产代码中使用
    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
    async
    /
    await
    to Kotlin Coroutines using references/dependencies-and-concurrency.md.
  • Convert ObservableObjects into Android
    ViewModel
    instances with
    SavedStateHandle
    using references/architecture-and-viewmodels.md.
  • Convert
    @State
    ,
    @Binding
    , and Combine publishers into
    mutableStateOf
    ,
    StateFlow
    , and
    SharedFlow
    with
    collectAsStateWithLifecycle
    using references/state-and-reactive-flows.md.
  • MANDATORY LIFECYCLE AWARENESS : When observing ViewModel
    StateFlow
    or
    SharedFlow
    streams inside Jetpack Compose screens, ALWAYS use
    collectAsStateWithLifecycle()
    from
    androidx.lifecycle.compose.collectAsStateWithLifecycle
    . NEVER use standard
    collectAsState()
    .
    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.
  • Mandatory Named Arguments for Dependency Wiring : When instantiating repositories, use cases, and ViewModels in
    AppContainer.kt
    or
    MainActivity.kt
    , always use Kotlin named arguments (e.g.
    ItemRepository(context = this, api = api)
    ). This eliminates swapped parameter compilation errors between the class definition and its call site.
  • API Keys & Secrets Rules : Never hardcode secrets in source code. Place API keys into
    local.properties
    and read them via Gradle
    buildConfigField
    or secure credential providers.
转换业务逻辑、网络服务、响应式状态管理和外部 API 配置。
  • 使用 references/dependencies-and-concurrency.md 将 CocoaPods/Swift Package Manager 库和 Swift
    async
    /
    await
    映射到 Kotlin Coroutines。
  • 使用 references/architecture-and-viewmodels.md 将 ObservableObjects 转换为使用
    SavedStateHandle
    的 Android
    ViewModel
    实例。
  • 使用 references/state-and-reactive-flows.md 将
    @State
    、
    @Binding
    和 Combine publisher 转换为
    mutableStateOf
    、
    StateFlow
    和
    SharedFlow
    ,并结合
    collectAsStateWithLifecycle
    使用。
  • 强制生命周期感知:在 Jetpack Compose 屏幕中观察 ViewModel 的
    StateFlow
    或
    SharedFlow
    流时,始终使用
    androidx.lifecycle.compose.collectAsStateWithLifecycle
    中的
    collectAsStateWithLifecycle()
    。绝不要使用标准
    collectAsState()
    。
    collectAsState()
    不会在应用进入后台或屏幕关闭时暂停收集,从而持续消耗资源并通过保持传感器、数据库查询和网络流活跃而浪费电量。
  • 依赖接线强制使用命名参数:在
    AppContainer.kt
    或
    MainActivity.kt
    中实例化 repository、use case 和 ViewModel 时,始终使用 Kotlin 命名参数,例如
    ItemRepository(context = this, api = api)
    。这样可以避免类定义与调用点之间参数顺序互换导致编译错误。
  • API Key 与密钥规则:绝不能将密钥硬编码到源代码中。将 API Key 放入
    local.properties
    ,并通过 Gradle
    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
      val CustomBrandBlue = Color(...)
      ). This causes unresolved reference errors across packages and breaks theme adaptability.
    • Map all branding and palette colors extracted from iOS asset catalogs (
      Assets.xcassets
      ) directly into the
      ColorScheme
      definition in
      ui/theme/Theme.kt
      (using standard slots like
      primary
      ,
      secondary
      ,
      tertiary
      ,
      surface
      ,
      surfaceVariant
      ,
      error
      ) or into a custom
      ExtendedColorScheme
      provided via
      CompositionLocalProvider
      .
    • In screen composables, access colors strictly via
      MaterialTheme.colorScheme.<slot>
      or semantic design system tokens. This guarantees zero missing imports across any package and automated Dark/Light theme switching.
  • Mandatory Edge-to-Edge : Implement
    enableEdgeToEdge()
    on the host Activity and properly handle
    WindowInsets
    across all composable screens.
  • Compose Previews : Every top-level composable screen MUST include a matching
    @Preview
    function to enable visual validation.
  • 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
      @Composable
      screens using
      rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
      (or
      PermissionController.createRequestPermissionResultContract()
      for Health Connect).
    • NEVER fall back to legacy Activity-level
      registerForActivityResult()
      inside
      MainActivity.kt
      unless there is no composable-compliant permission alternative available for that specific platform capability.
    • NEVER simulate platform permissions with mock boolean flags in repositories or bypass real permission checks.
  • Compose Layout Anti-Squeeze Invariant : In every
    Row
    that places flexible content (a title/description
    Text
    or
    Column
    ) beside fixed-intent elements (a
    Button
    , price or badge
    Text
    ,
    FilterChip
    ,
    SegmentedButton
    ,
    IconButton
    ,
    Switch
    ), apply
    Modifier.weight(1f)
    to the flexible side and
    maxLines = 1
    to the fixed element's
    Text
    ; otherwise Compose squeezes the fixed element and wraps its label one character per line on a typical phone width (roughly 360--411dp).
    Arrangement.SpaceBetween
    is 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 option
    Modifier.weight(1f)
    . Worked examples: references/ui-layout-swiftui-to-compose.md.
  • String Resources Are Referenced, Not Just Declared : SwiftUI
    Text("Literal")
    is an implicit
    LocalizedStringKey
    lookup; Compose
    Text("Literal")
    is not. Every user-facing string --- text, button and chip labels, titles,
    contentDescription
    , snackbar/dialog text, and custom-component
    text
    /
    title
    /
    label
    arguments, including strings the iOS code wrote inline --- must come from
    stringResource(R.string....)
    . A
    strings.xml
    the UI never references does not count. Also:
    • Strings first, per screen : before writing each composable, add that screen's user-facing strings to
      strings.xml
      --- the iOS view's inline literals as well as its localized keys (
      String(localized:)
      ,
      NSLocalizedString
      , or generated accessors such as SwiftGen's
      L10n
      / R.swift), reusing existing entries --- then write the composable against
      R.string
      keys. Don't defer extraction to a clean-up pass.
    • Dynamic text uses format arguments , never concatenation or string templates (
      <string name="trail_distance">Distance: %1$s</string>
      →
      stringResource(R.string.trail_distance, distance)
      ); concatenated fragments cannot be translated or reordered.
    • Display names on models and enums (goals, categories, levels) hold a
      @StringRes Int
      resolved in the UI, not a raw
      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.
使用 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 中,严格通过
      MaterialTheme.colorScheme.<slot>
      或语义设计系统 token 访问颜色。这样可以保证跨包引用时不会出现缺失 import,并支持自动进行 Dark/Light 主题切换。
  • 强制 Edge-to-Edge:在宿主 Activity 中实现
    enableEdgeToEdge()
    ,并在所有 composable 屏幕中正确处理
    WindowInsets
    。
  • Compose Preview:每个顶层 composable 屏幕都必须包含匹配的
    @Preview
    函数,以支持视觉验证。
  • 使用 references/navigation-compose.md 实现类型安全的屏幕路由与底部导航。
  • 使用 references/ui-animations.md 复刻布局转场、基于物理的弹簧动画和共享元素。
  • Jetpack Compose 运行时权限协议:
    • 在 Jetpack Compose 应用中,运行时权限必须在
      @Composable
      屏幕内通过
      rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
      请求;Health Connect 则使用
      PermissionController.createRequestPermissionResultContract()
      。
    • 绝不要回退到
      MainActivity.kt
      中旧式的 Activity 级
      registerForActivityResult()
      ,除非该特定平台能力不存在任何符合 Compose 规范的权限替代方案。
    • 绝不要在 repository 中使用 mock boolean 标志模拟平台权限,也不得绕过真实权限检查。
  • Compose 布局防挤压不变量:在每个
    Row
    中,如果固定意图元素(
    Button
    、价格或徽标
    Text
    、
    FilterChip
    、
    SegmentedButton
    、
    IconButton
    、
    Switch
    )旁放置了可伸缩内容(标题/描述
    Text
    或
    Column
    ),必须对可伸缩一侧应用
    Modifier.weight(1f)
    ,并对固定元素的
    Text
    设置
    maxLines = 1
    ;否则在典型手机宽度(约 360--411dp)下,Compose 会挤压固定元素,使其标签逐字符换行。
    Arrangement.SpaceBetween
    不能替代
    weight
    。多选项选择器(segmented button、chip group)应放在标题下方的独立全宽行中,并为每个选项应用
    Modifier.weight(1f)
    。可参考 references/ui-layout-swiftui-to-compose.md 中的示例。
  • 字符串资源必须被引用,而不只是声明:SwiftUI 的
    Text("Literal")
    隐式执行
    LocalizedStringKey
    查找,而 Compose 的
    Text("Literal")
    不会。每个面向用户的字符串——文本、按钮和 chip 标签、标题、
    contentDescription
    、snackbar/dialog 文本,以及自定义组件的
    text
    /
    title
    /
    label
    参数,包括 iOS 代码内联写入的字符串——都必须来自
    stringResource(R.string....)
    。UI 从未引用的
    strings.xml
    不算完成。同时:
    • 按屏幕优先处理字符串:编写每个 composable 之前,先将该屏幕面向用户的字符串添加到
      strings.xml
      ——包括 iOS 视图中的内联字面量和本地化键(
      String(localized:)
      、
      NSLocalizedString
      ,或 SwiftGen 的
      L10n
      /R.swift 等生成的 accessor)——并复用已有条目——然后使用
      R.string
      键编写 composable。不要将提取工作推迟到最后清理阶段。
    • 动态文本使用格式参数,绝不能使用字符串拼接或模板(
      <string name="trail_distance">Distance: %1$s</string>
      →
      stringResource(R.string.trail_distance, distance)
      );拼接的片段无法翻译或重新排序。
    • 模型和枚举上的显示名称(目标、类别、等级)保存
      @StringRes Int
      ,并在 UI 中解析,而不是保存原始
      String
      。
    • Composition 之外的文本(通知、toast、前台服务通知、widget)使用
      context.getString(...)
      。
    • Preview、日志消息和非面向用户的键(路由、测试标签、channel ID)不受此限制。

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
    Info.plist
    → Android 14+ permission mapping table, the
    rememberPermissionRequest
    hook pattern, Health Connect's dedicated permission contract, and the two-step background location flow. Every dangerous permission declared in
    AndroidManifest.xml
    requires 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.
  • Camera : Consult references/camera-camerax.md for CameraX preview (
    PreviewView
    inside Compose
    AndroidView
    ) and
    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
    WorkManager
    constraints and periodic jobs.
[!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
SharedPreferences
. Implement the real Android SDK in each manager/service class. Wrap hardware/SDK calls in
try/catch
so 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 inside
try/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 or
#if targetEnvironment(simulator)
, port that gate (a DataStore preference or
BuildConfig.DEBUG
); never call a demo-data loader unconditionally from
init
or from a scan/read entry point. 1. Runtime permissions : see Runtime Permission Invariants below.
@SuppressLint("MissingPermission")
is not a permission implementation; it is allowed only on a call site guarded by
ContextCompat.checkSelfPermission(...) == PackageManager.PERMISSION_GRANTED
. 2. Health Connect :
HealthConnectClient.getOrCreate(context)
,
HealthPermission.getReadPermission(...)
/
getWritePermission(...)
for the record types matching the HealthKit types the source app reads and writes,
readRecords(ReadRecordsRequest(...))
and
insertRecords(...)
. See references/health-connect.md. 3. Google Play Billing :
BillingClient.newBuilder(context).setListener(purchasesUpdatedListener).enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()).build()
; a
BillingClientStateListener
whose
onBillingServiceDisconnected()
actually reconnects (for example with exponential backoff, or reconnect-on-next-request) rather than only logging;
queryProductDetailsAsync
,
launchBillingFlow(activity, params)
, and
acknowledgePurchase
. 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 an
else
branch. See references/in-app-billing.md. 4. Bluetooth LE :
BluetoothManager
→
BluetoothLeScanner.startScan(filters, settings, scanCallback)
with a concrete
ScanCallback
, and a concrete
BluetoothGattCallback
(
onConnectionStateChange
,
onServicesDiscovered
,
onCharacteristicChanged
parsing the GATT characteristics the iOS code reads). Manifest:
BLUETOOTH_SCAN
(with
android:usesPermissionFlags="neverForLocation"
unless location is derived from scans) and
BLUETOOTH_CONNECT
, both requested at runtime; legacy
BLUETOOTH
/
BLUETOOTH_ADMIN
and any scan-only
ACCESS_FINE_LOCATION
limited with
android:maxSdkVersion="30"
. See references/bluetooth-ble.md. 5. Location :
LocationServices.getFusedLocationProviderClient(context)
with
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMillis)
and a
LocationCallback
(
requestLocationUpdates
/
removeLocationUpdates
). When tracking must continue after the UI leaves the screen (iOS
allowsBackgroundLocationUpdates
/
UIBackgroundModes: location
), add a
Service
that calls
startForeground
with an ongoing notification, declared with
android:foregroundServiceType="location"
plus
FOREGROUND_SERVICE
and
FOREGROUND_SERVICE_LOCATION
. Don't declare
ACCESS_BACKGROUND_LOCATION
unless 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 : a
CoroutineWorker
scheduled with
WorkManager.getInstance(context).enqueueUniquePeriodicWork(..., ExistingPeriodicWorkPolicy.KEEP, PeriodicWorkRequestBuilder<...>(...).setConstraints(...).build())
, mirroring the iOS task's cadence and constraints. See references/background-tasks-workmanager.md.
根据步骤 2 中识别出的结果,有条件地加载并执行特定领域平台服务:
  • 运行时权限:查阅 references/permissions-runtime.md,了解 iOS
    Info.plist
    到 Android 14+ 权限映射表、
    rememberPermissionRequest
    hook 模式、Health Connect 专用 permission contract,以及分两步进行的后台定位流程。
    AndroidManifest.xml
    中声明的每项危险权限都必须有对应的运行时请求
    ——仅声明 Manifest 条目不会授予任何权限,请求必须呈现真实的系统对话框,而不是应用内替代界面。
  • 相机:查阅 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 或
SharedPreferences
替换平台 SDK。必须在每个 manager/service 类中实现真实的 Android SDK。使用
try/catch
包装硬件/SDK 调用,使 JVM 单元测试以及缺少硬件或 SDK 的设备不会崩溃;这只用于处理缺少硬件,绝不能用于绕过缺少权限——应先检查权限,然后在
try/catch
中调用。示例/demo 数据仅允许在 SDK 不可用或用户拒绝权限时作为 fallback;绝不能将其混入真实结果,也绝不能授予 entitlement。如果源代码通过用户设置、debug flag 或
#if targetEnvironment(simulator)
控制示例/demo 数据,则应移植该开关(使用 DataStore 偏好或
BuildConfig.DEBUG
);绝不能从
init
或扫描/读取入口无条件调用 demo data loader。1. 运行时权限:参见下方的运行时权限不变量。
@SuppressLint("MissingPermission")
不是权限实现;只有在调用位置受
ContextCompat.checkSelfPermission(...) == PackageManager.PERMISSION_GRANTED
保护时才允许使用。2. Health Connect:使用
HealthConnectClient.getOrCreate(context)
;针对与源应用读写 HealthKit 类型相匹配的记录类型,使用
HealthPermission.getReadPermission(...)
/
getWritePermission(...)
、
readRecords(ReadRecordsRequest(...))
和
insertRecords(...)
。参见 references/health-connect.md。3. Google Play Billing:使用
BillingClient.newBuilder(context).setListener(purchasesUpdatedListener).enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build()).build()
;其
BillingClientStateListener.onBillingServiceDisconnected()
必须实际重新连接,例如使用指数退避或在下一次请求时重连,而不是只记录日志;还要实现
queryProductDetailsAsync
、
launchBillingFlow(activity, params)
和
acknowledgePurchase
。可以显示占位价格作为 fallback,但在客户端未就绪或没有 Activity 时购买必然失败——应删除 mock 购买代码,而不是将其保留为
else
分支。参见 references/in-app-billing.md。4. Bluetooth LE:使用
BluetoothManager
→
BluetoothLeScanner.startScan(filters, settings, scanCallback)
,并提供具体的
ScanCallback
;还要提供具体的
BluetoothGattCallback
(
onConnectionStateChange
、
onServicesDiscovered
、
onCharacteristicChanged
),解析 iOS 代码读取的 GATT characteristic。Manifest:
BLUETOOTH_SCAN
(除非扫描结果用于推导位置,否则使用
android:usesPermissionFlags="neverForLocation"
)和
BLUETOOTH_CONNECT
,两者都必须在运行时请求;旧式
BLUETOOTH
/
BLUETOOTH_ADMIN
以及仅用于扫描的
ACCESS_FINE_LOCATION
应使用
android:maxSdkVersion="30"
加以限制。参见 references/bluetooth-ble.md。5. 位置:使用
LocationServices.getFusedLocationProviderClient(context)
,配合
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMillis)
和
LocationCallback
(
requestLocationUpdates
/
removeLocationUpdates
)。当跟踪必须在 UI 离开屏幕后继续时(iOS
allowsBackgroundLocationUpdates
/
UIBackgroundModes: location
),添加一个调用
startForeground
并显示持续通知的
Service
,在 Manifest 中声明
android:foregroundServiceType="location"
,同时添加
FOREGROUND_SERVICE
和
FOREGROUND_SERVICE_LOCATION
。除非某条代码路径在没有可见 UI 和前台服务的情况下读取位置,否则不要声明
ACCESS_BACKGROUND_LOCATION
;绝不能声明迁移代码未使用的权限。参见 references/location-fusedprovider.md。6. WorkManager:使用
CoroutineWorker
,通过
WorkManager.getInstance(context).enqueueUniquePeriodicWork(..., ExistingPeriodicWorkPolicy.KEEP, PeriodicWorkRequestBuilder<...>(...).setConstraints(...).build())
调度,并映射 iOS 任务的频率和约束。参见 references/background-tasks-workmanager.md。

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
rememberPermissionRequest
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.
[!CAUTION] Caution: The runtime prompt MUST be the real Android system dialog, launched through
rememberLauncherForActivityResult
from 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 static
hasXPermission()
helpers. Checking is not requesting. * ❌ A permission helper or launcher that is defined or imported but never invoked from a screen. * ❌
if (granted) ScreenContent() else PermissionScreen()
. Permission state may disable a control or populate an empty state; it must never replace the screen.
  • 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
    +
    BLUETOOTH_CONNECT
    ; the screen or sheet that opens the camera →
    CAMERA
    , before binding CameraX (the most commonly missed request); app entry →
    POST_NOTIFICATIONS
    on API 33+ (from a
    LaunchedEffect
    , without gating content).
  • Health Connect uses
    PermissionController.createRequestPermissionResultContract()
    , not
    RequestMultiplePermissions()
    . The action that reads health data must first call
    permissionController.getGrantedPermissions()
    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.
  • 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 虽然能够干净编译,却只会在运行时失败。完整模式——
rememberPermissionRequest
状态 hook、调用点 guard、Health Connect contract、分两步进行的后台定位,以及验证检查清单——位于 references/permissions-runtime.md 中。编写权限代码前必须阅读该文档。
[!CAUTION] 注意:运行时提示必须是由
rememberLauncherForActivityResult
启动的真实 Android 系统对话框,并且必须从需要权限的用户操作触发。未授予权限时,屏幕仍必须渲染其内容。
以下形式均属于
失败迁移
:* ❌ 仅包含静态
hasXPermission()
helper 的工具对象。检查权限不等于请求权限。* ❌ 定义或导入 permission helper/launcher,却从未在屏幕中调用。* ❌
if (granted) ScreenContent() else PermissionScreen()
。权限状态可以禁用控件或填充空状态,但绝不能替换整个屏幕。
  • 使用点:从需要权限的操作发起每项危险权限请求——例如启动位置跟踪的控件 → fine/coarse location;扫描 BLE 设备的控件 →
    BLUETOOTH_SCAN
    +
    BLUETOOTH_CONNECT
    ;打开相机的屏幕或 sheet →
    CAMERA
    ,并在绑定 CameraX 前请求(最常被遗漏);应用入口 → API 33+ 上的
    POST_NOTIFICATIONS
    (通过
    LaunchedEffect
    发起,但不以此控制内容显示)。
  • Health Connect 使用
    PermissionController.createRequestPermissionResultContract()
    ,而不是
    RequestMultiplePermissions()
    。读取健康数据的操作必须先调用
    permissionController.getGrantedPermissions()
    ,并在缺少权限时启动请求。只有在拒绝权限或 SDK 不可用时才能回退到示例数据,绝不能以示例数据代替权限请求。
  • 后台位置是在授予前台位置权限之后发起的第二次独立请求,并且仅在确有代码路径需要时执行。
  • 如果源应用具有自己的权限说明 UI,应将其移植为非阻塞式 banner、card 或空状态,并提供请求操作入口。
  • 在
    AndroidManifest.xml
    中声明了危险权限,却没有任何从屏幕可达的运行时请求,属于失败迁移,必须在步骤 10 的完成前检查清单中验证。

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:
      1. Data & Domain Gate : After implementing domain models, Room entities, DAOs, and repositories, execute
        ./gradlew compileDebugKotlin
        to verify the foundational data layer compiles cleanly before touching the UI.
      2. Vertical Feature Slicing for UI : Author UI feature-by-feature (
        ViewModel
        ➡️
        Screen Composable
        ➡️
        Route
        ). Before implementing a screen, inspect the corresponding
        ViewModel
        state data class and domain models to ensure 100% property name and type fidelity.
      3. Per-Slice Verification : Run
        ./gradlew compileDebugKotlin
        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.
    • At the conclusion of migration, execute
      ./gradlew :app:assembleDebug
      and
      ./gradlew :app:testDebugUnitTest
      . Both MUST exit 0.
  • Pre-Completion Checklist (run every item before finishing; each is a search, not a recollection) :
    1. Debugging stubs restored : anything you stubbed, moved or commented out to isolate a failure (e.g. a minimal
      setContent { Text("test") }
      ) is restored;
      MainActivity.kt
      hosts the real theme and navigation graph; no temporary directories or placeholder composables remain.
    2. Permissions : every permission helper has a call site outside its own definition, and every dangerous permission in
      AndroidManifest.xml
      (e.g.
      CAMERA
      , location, Bluetooth, notifications, Health Connect) appears in a runtime request reached from a screen.
    3. Strings : search UI and notification code for
      Text("
      ,
      text = "
      ,
      title = "
      ,
      label = "
      ,
      contentDescription = "
      ,
      setContentTitle("
      /
      setContentText("
      , and string templates containing
      $
      in UI files; move every user-facing hit into
      strings.xml
      per Step 8.
    4. Platform managers: no demo/sample-data loader is called unconditionally (Step 9 contract); every hardware/SDK path calls the real Android API.
    5. Database : if
      createFromAsset()
      is used, schema parity is proven per Step 6; no Room query runs on the main thread.
    6. Re-run
      ./gradlew :app:assembleDebug
      and
      ./gradlew :app:testDebugUnitTest
      ; both exit 0.
  • 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
    snapshot
    ), port it using references/screenshots-screengrab.md.
  • Prioritized Quality Gate & Refinement Triage : Follow this strict 3-tier feedback protocol when validating:
    1. Priority #1: Stability (Crashes): Fix all unhandled exceptions, KSP annotation crashes, or runtime crashes immediately. Iterate until the app is stable.
    2. Priority #2: Core Feature Parity : Check that all CUJs and top-level navigation tabs in
      feature_specification.md
      are implemented with complete, functional Material 3 screens across the full navigation graph. Trigger at most a single (one-time) refinement loop per feature.
    3. 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
    .migration/migration_walkthrough.md
    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.

验证迁移后的 Android 应用功能完整、测试充分且文档完善。
  • 增量分层编译与垂直切片关卡:
    • 为防止大型多文件迁移在后期产生连锁编译错误,必须遵守增量编译关卡:
      1. 数据与领域关卡:实现领域模型、Room entity、DAO 和 repository 后,执行
        ./gradlew compileDebugKotlin
        ,确认基础数据层能够在 UI 开发前干净编译。
      2. UI 垂直功能切片:逐个功能编写 UI(
        ViewModel
        ➡️
        Screen Composable
        ➡️
        Route
        )。实现屏幕之前,检查对应的
        ViewModel
        状态 data class 和领域模型,确保属性名称与类型完全一致。
      3. 逐切片验证:每完成一个功能切片(或每两个屏幕)后,运行
        ./gradlew compileDebugKotlin
        。立即捕获属性不匹配或语法错误只需数秒,并能保证最终构建干净。
    • 迁移结束时,执行
      ./gradlew :app:assembleDebug
      和
      ./gradlew :app:testDebugUnitTest
      。两者都必须以状态码 0 退出。
  • 完成前检查清单(结束前逐项执行;每项都应执行搜索,而不是凭记忆确认):
    1. 恢复调试 stub:为隔离故障而 stub、移动或注释的任何内容,例如最小的
      setContent { Text("test") }
      ,都必须恢复;
      MainActivity.kt
      必须承载真实主题和导航图;不得残留临时目录或占位 composable。
    2. 权限:每个 permission helper 都必须在自身定义之外存在调用点;
      AndroidManifest.xml
      中的每项危险权限,例如
      CAMERA
      、位置、Bluetooth、通知、Health Connect,都必须出现在从屏幕可达的运行时请求中。
    3. 字符串:在 UI 和通知代码中搜索
      Text("
      、
      text = "
      、
      title = "
      、
      label = "
      、
      contentDescription = "
      、
      setContentTitle("
      /
      setContentText("
      ,以及 UI 文件中包含
      $
      的字符串模板;按照步骤 8 将每个面向用户的命中项移入
      strings.xml
      。
    4. 平台 manager:不得无条件调用 demo/sample-data loader(步骤 9 契约);每条硬件/SDK 路径都必须调用真实的 Android API。
    5. 数据库:如果使用
      createFromAsset()
      ,必须按照步骤 6 证明 schema 一致;任何 Room 查询都不能在主线程运行。
    6. 重新运行
      ./gradlew :app:assembleDebug
      和
      ./gradlew :app:testDebugUnitTest
      ;两者都以状态码 0 退出。
  • 回合完成:启动后台构建后,不要结束回合或输出等待消息;应继续工作或等待构建完成。
  • 使用 references/testing-unit-and-compose.md 将 XCTest 单元测试移植到 JUnit5/MockK,并将 XCUITest 用户流程移植到 Compose UI 测试。
  • 如果 iOS 项目通过 fastlane
    snapshot
    自动执行截图测试,应使用 references/screenshots-screengrab.md 进行移植。
  • 优先级质量关卡与改进分流:验证时遵循严格的 3 层反馈协议:
    1. 优先级 #1:稳定性(崩溃):立即修复所有未处理异常、KSP 注解崩溃或运行时崩溃。持续迭代,直到应用稳定。
    2. 优先级 #2:核心功能一致性:检查
      feature_specification.md
      中的所有 CUJ 和顶层导航标签是否都已在完整导航图中实现为功能完整、可用的 Material 3 屏幕。每个功能最多触发**一次(单次)**改进循环。
    3. 优先级 #3:严重 UI 缺陷:解决明显的布局破坏(padding、裁剪、margin)、突兀的默认样式、缺失的 drawable,以及 Edge-to-Edge 合规问题。忽略轻微的外观或排版细节问题,避免反复折腾。
  • 生成迁移说明:编写
    .migration/migration_walkthrough.md
    ,记录所有已转换组件、验证结果和架构决策。每项“已实现 X”的声明都必须指出实际使用 X 的文件,而不只是定义它的文件——例如实际调用权限请求的屏幕/按钮。如果无法指出调用点,则该功能尚未实现;必须返回并完成接线。

Antipatterns

反模式

DO

应该做

  • DO run the automated project audit before writing any code.
  • DO preserve the existing
    namespace
    ,
    applicationId
    , 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 (
    app/build.gradle.kts
    ,
    libs.versions.toml
    ) to add libraries/plugins required for functionality being ported.
  • 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
    NavHost
    graph.
  • DO declare in
    AndroidManifest.xml
    the Android 14+ permission for every iOS
    Info.plist
    privacy key the app actually uses (see the mapping table in references/permissions-runtime.md).
  • DO ensure all added permissions are requested at runtime according to Jetpack Compose best practices using
    rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
    (and Health Connect permission request contracts) rather than only declaring them in the manifest.
  • DO keep UI strings in
    res/values/strings.xml
    and colors in a Light + Dark Material 3 theme, migrate relational data to Room (
    @Entity
    ,
    @Dao
    ,
    RoomDatabase
    exposing
    Flow
    ), and use
    DataStore<Preferences>
    for key-value settings.
  • DO produce a formal
    feature_specification.md
    capturing non-obvious logic and data flows.
  • DO verify the complete migration with a consolidated compile and test check (
    ./gradlew assembleDebug
    and
    ./gradlew testDebugUnitTest
    ) at the conclusion of code generation.
  • DO load only the specific reference files flagged during the initial audit.
  • DO use Jetpack Compose, Material Design 3, and
    enableEdgeToEdge()
    for all UI screens, collecting state via
    collectAsStateWithLifecycle()
    and using explicit
    key = { ... }
    in
    LazyColumn
    items.
  • DO isolate all secrets and API keys in
    local.properties
    .
  • DO generate
    @Preview
    functions for every top-level composable screen.
  • 应该在编写任何代码之前执行自动化项目审计。
  • 应该在迁移到现有 Android 项目骨架时保留现有
    namespace
    、
    applicationId
    和根包结构——仅在没有任何现有项目/Gradle 文件时生成全新的项目和 Gradle 文件,并且只更新 Gradle 配置(
    app/build.gradle.kts
    、
    libs.versions.toml
    )以添加功能移植所需的库/插件。
  • 应该根据上下文调整包架构:小巧的单功能工具使用紧凑文件(< 1,000 LOC);复杂的多流程应用使用完整多包架构(> 1,000 LOC/5 个以上屏幕),并确保源应用的每个屏幕都可从
    NavHost
    图中到达。
  • 应该在
    AndroidManifest.xml
    中为应用实际使用的每个 iOS
    Info.plist
    隐私键声明对应的 Android 14+ 权限,参见 references/permissions-runtime.md 中的映射表。
  • 应该按照 Jetpack Compose 最佳实践,使用
    rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
    (以及 Health Connect 权限请求 contract)在运行时请求所有新增权限,而不是仅在 Manifest 中声明。
  • 应该将 UI 字符串保留在
    res/values/strings.xml
    中,将颜色放入 Light + Dark Material 3 主题,将关系数据迁移到 Room(
    @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
    settings.gradle.kts
    , root
    build.gradle.kts
    , or
    app/build.gradle.kts
    from scratch or change the root
    namespace
    /package name when migrating into an existing Android project shell.
  • DON'T collapse a complex multi-screen application into a single monolithic
    MainActivity.kt
    file or use barebones test-tag stub buttons instead of functional Material 3 screens.
  • DON'T declare permissions in
    AndroidManifest.xml
    without also implementing runtime permission requests (
    rememberLauncherForActivityResult
    ) in the UI layer.
  • 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
    references/
    without first reading and following the primary orchestration protocol in
    SKILL.md
    .
  • DON'T translate Swift code line-by-line; translate concepts, architectural boundaries, and behaviors.
  • DON'T use legacy Android XML Views,
    findViewById
    , or
    AsyncTask
    in new migrations.
  • DON'T fail silently on unsupported or proprietary iOS APIs.
  • 不应该在没有真实、已验证且显示状态码 0 的 CLI 执行输出时宣称迁移成功。
  • 不应该从头覆盖现有
    settings.gradle.kts
    、根
    build.gradle.kts
    或
    app/build.gradle.kts
    ,也不应该在迁移到现有 Android 项目骨架时更改根
    namespace
    /包名。
  • 不应该将复杂的多屏幕应用折叠成单个巨型
    MainActivity.kt
    文件,也不应该使用只有测试标签的简陋 stub 按钮代替功能完整的 Material 3 屏幕。
  • 不应该只在
    AndroidManifest.xml
    中声明权限,却不在 UI 层实现运行时权限请求(
    rememberLauncherForActivityResult
    )。
  • 不应该因轻微的外观或排版差异进入无限改进循环。
  • 不应该一次性将所有补充参考文件加载到 agent 的上下文中。
  • 不应该在未阅读并遵循
    SKILL.md
    中主要编排协议的情况下访问
    references/
    中的文件。
  • 不应该逐行翻译 Swift 代码;应转换其概念、架构边界和行为。
  • 不应该在新迁移中使用旧式 Android XML Views、
    findViewById
    或
    AsyncTask
    。
  • 不应该对不支持或专有的 iOS API 静默失败。

NEVER

绝不允许

  • NEVER finalize a migration without verifying that
    ./gradlew assembleDebug
    exits 0.
  • 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
    TODO
    comments in production Kotlin source files.
  • NEVER ignore iOS
    Info.plist
    permissions during the initial audit phase.
  • 绝不在未验证
    ./gradlew assembleDebug
    以状态码 0 退出的情况下结束迁移。
  • 绝不在未编写所请求 Kotlin 实现 diff 的情况下结束回合,或输出“正在等待测试/构建完成……”之类的消息。
  • 绝不在源代码或版本控制中硬编码 API Key、密钥或 token。
  • 绝不在生产 Kotlin 源文件中留下空占位函数或
    TODO
    注释。
  • 绝不在初始审计阶段忽略 iOS
    Info.plist
    权限。