# Capacitor Android 打包 ## 前置环境 1. **Node.js** ≥ 18(项目用 22) 2. **JDK 17**(`java -version` 可验证) 3. **Android Studio** + Android SDK(API 34) 4. 配好 `ANDROID_HOME` 或 `ANDROID_SDK_ROOT` 环境变量 ## 一次性配置 ```bash cd frontend npm install # 构建前端静态资源到 dist/ npm run build # 初始化 Capacitor + 创建 android 壳工程 npx cap init cn.myhomepage.app MyHomePage --web-dir=dist npx cap add android ``` ## 每次更新 ```bash # 1. 改完前端代码 npm run build # 2. 同步到 android 工程 npx cap sync android # 3. 在 Android Studio 中打开并打包 npx cap open android # 或命令行: cd android ./gradlew assembleDebug # 调试 APK → android/app/build/outputs/apk/debug/ ./gradlew assembleRelease # 发布 APK(需先在 build.gradle 配签名) ``` ## APP 内后端地址 APP 内不能使用 vite proxy,必须指向真实后端: 修改 `frontend/.env.production`: ``` VITE_API_BASE=http://10.0.2.2:5080 # Android 模拟器访问宿主机 # 或: VITE_API_BASE=https://your-domain.com ``` 然后 `npm run build` 重新构建。 ## 网络权限 首次 `npx cap add android` 后,在 `android/app/src/main/AndroidManifest.xml` 的 `` 标签里加: ```xml android:usesCleartextTraffic="true" ``` (如已在 `capacitor.config.ts` 中设 `cleartext: true`,则通常已自动加好) ## 常见问题 - **空白页 / 加载失败**:检查 `VITE_API_BASE` 是否填写,后端是否允许 CORS - **CORS 报错**:在 `backend/appsettings.json` 的 `Cors.Origins` 中加上 `capacitor://localhost` 和 `http://localhost` - **图片显示 404**:`Upload.BaseUrl` 与 `appsettings.{Env}.json` 保持一致,建议反代