v1.6.0 #13
@@ -281,8 +281,22 @@ jobs:
|
||||
API_TOKEN: ${{ secrets.TIMI_API_TOKEN }}
|
||||
RELEASE_ID: ${{ steps.create.outputs.release_id }}
|
||||
run: |
|
||||
curl -sS -X POST "$API_BASE_URL/app/release/publish?releaseId=$RELEASE_ID&channelCode=stable" \
|
||||
-H "Token: $API_TOKEN"
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
echo "FAIL: 缺少发布记录 ID"
|
||||
exit 1
|
||||
fi
|
||||
# -f 让 4xx/5xx 直接失败;否则下面那句 OK 会照打,tag 也会照建
|
||||
response=$(curl -sS -f -X POST "$API_BASE_URL/app/release/publish?releaseId=$RELEASE_ID&channelCode=stable" \
|
||||
-H "Token: $API_TOKEN") || {
|
||||
echo "FAIL: 发布接口调用失败"
|
||||
exit 1
|
||||
}
|
||||
echo "响应:$response"
|
||||
# 业务层异常仍可能是 200 + fail:true,这里再兜一层
|
||||
if printf '%s' "$response" | grep -qE '"fail"[[:space:]]*:[[:space:]]*true|"success"[[:space:]]*:[[:space:]]*false'; then
|
||||
echo "FAIL: 发布未生效,请检查后端日志"
|
||||
exit 1
|
||||
fi
|
||||
echo "OK: 已发布到 stable"
|
||||
|
||||
# 打 tag 的时机是「上线成功」而不是「PR 合并」:草稿发布和失败发布都不该留下版本标记。
|
||||
|
||||
@@ -154,3 +154,4 @@ release-note.txt
|
||||
# Android Studio 本地配置及发布构建产物
|
||||
/android/.idea/
|
||||
/android/app/release/
|
||||
/android/keystore.properties
|
||||
|
||||
@@ -19,6 +19,31 @@ CI 规则(.gitea/workflows/release.yml):
|
||||
需要更正请发补丁版本
|
||||
-->
|
||||
|
||||
## v1.6.0
|
||||
|
||||
### 新增
|
||||
|
||||
- App 端支持拍照、录视频时写入系统相册
|
||||
- 积分兑换的库存流水可以跳转对应积分兑换单
|
||||
- 登记事件记录日历显示客户照片
|
||||
- 新增和优化回收物流水、订单回收物、客户回收物页面
|
||||
- 库存日历的当日流水支持直接弹出查看详情
|
||||
- 让 ChatGPT 设计了一个好好看的图标
|
||||
|
||||
### 调整
|
||||
|
||||
- 更多页面适配平板横屏模式:积分、消费、套餐
|
||||
- 现在积分兑换凭证会同步兑换产品出库记录
|
||||
- 积分兑换的库存流水现在显示客户姓名而不是操作用户名
|
||||
- 顶部弹出消息不再遮挡导航栏
|
||||
|
||||
### 修复
|
||||
|
||||
- 拍照照片压缩后可能出现只有 1/4 大小,其余留白,并且发生旋转
|
||||
- 平板横屏下阅读站内通知时列表没有刷新已读状态
|
||||
- App 端顶部弹出消息偏移不足,导致和状态栏重合
|
||||
- 部分页面样式
|
||||
|
||||
## v1.5.0
|
||||
|
||||
### 调整
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
# 原生能力预埋清单
|
||||
|
||||
> 适用范围:gao-customer-h5 的 Android 原生壳(Capacitor 8)
|
||||
> 关联文档:`NATIVE_UPGRADE.md`(发壳流程)、`capacitor.config.ts`(插件配置)
|
||||
|
||||
## 这份文档解决什么
|
||||
|
||||
Capacitor 的原生能力集是**编译期固定**的:壳里没有的插件,热更包调不到。每加一个插件、每加一个权限,都必须重新发一次 APK。
|
||||
|
||||
本次升级(versionCode 3 → 4)的核心目的不是上线新功能,而是**把未来一到两年可能用到的原生能力一次性装进壳里**,此后业务迭代全部走热更。
|
||||
|
||||
因此有一条硬约束:
|
||||
|
||||
> **本次发壳后,Web 侧不得调用任何新能力**,直到业务真正需要。
|
||||
> 在 `APP_MIN_VERSION_CODE` 抬到 4 之前,老壳用户必须能正常收到热更。
|
||||
|
||||
---
|
||||
|
||||
## 一、能力清单
|
||||
|
||||
全部能力收在单个插件 `NativeKit` 下,避免注册表膨胀。前端只需 `registerPlugin("NativeKit")`。
|
||||
|
||||
| 分组 | 方法 | 说明 |
|
||||
|---|---|---|
|
||||
| 协商 | `getInfo()` | 返回壳版本、WebView 内核、能力名数组 |
|
||||
| 扫码 | `scan()` | 原生整页取景,QR / CODE_128 / CODE_39 / EAN_13 / EAN_8 |
|
||||
| 相机 | `capture()` | 单张或连拍,前后切换、闪光灯,返回原图 |
|
||||
| 下载 | `download()` | DownloadManager,落 `Downloads/GaoCustomer` |
|
||||
| 分享 | `share()` | 系统分享面板,发微信 / 企微 |
|
||||
| 打印 | `print()` | 系统打印框架,图片与 PDF |
|
||||
| 通知 | `scheduleNotification()` / `cancelNotification()` / `cancelAllNotifications()` / `listScheduledNotifications()` | 定时与每日/每周/每年重复,点击带路由,可按归属清理 |
|
||||
| 通知 | `getNotificationPermission()` / `requestNotificationPermission()` | Android 13+ 运行时权限 |
|
||||
| 通知 | `canScheduleExactAlarms()` / `openExactAlarmSettings()` | Android 12+ 精确闹钟授权 |
|
||||
| 语音 | `voiceAvailable()` / `voiceStart()` / `voiceStop()` / `voiceCancel()` | 系统识别双通道,含 partial 回调 |
|
||||
| 安全 | `biometricAvailable()` / `biometricUnlock()` | 指纹 / 面容解锁 |
|
||||
| 安全 | `saveSession()` / `readSession()` / `clearSession()` | Keystore 加密的登录态存储 |
|
||||
| 打印 | `listPrinters()` / `printRaw()` | 蓝牙 SPP + ESC/POS 原始字节 |
|
||||
| 文件 | `pickFile()` / `saveFile()` | SAF 选择与另存 |
|
||||
| 日历 | `calendarAvailable()` / `addCalendarEvent()` / `removeCalendarEvent()` | 写入系统日历,静默或拉起日历界面 |
|
||||
| 状态 | `appStateChange` / `networkStatusChange` 事件、`getAppState()` / `getNetworkStatus()` | 前后台与网络变化感知 |
|
||||
| 权限 | `getPermissionStates()` + 四个设置跳转 + `isIgnoringBatteryOptimizations()` | 授权状态查询与被拒后的补救入口 |
|
||||
| 设备 | `getDeviceId()` / `getRingerMode()` / `setKeepAwake()` / `setOrientation()` / `restartApp()` / `clearWebCache()` | 设备标识、响铃模式、常亮、方向、重启、清缓存 |
|
||||
| 通讯录 | `contactsAvailable()` / `addContact()` / `syncContacts()` / `clearContacts()` | 批量写入系统通讯录,供语音助手与来电识别使用 |
|
||||
| 杂项 | `vibrate()` / `copy()` / `getDeviceInfo()` | 震动、剪贴板、设备信息 |
|
||||
|
||||
### 明确不做的
|
||||
|
||||
| 项 | 原因 |
|
||||
|---|---|
|
||||
| 离线语音模型(Vosk / sherpa-onnx) | 体积 42MB 起,业务短句识别率未必优于系统引擎 |
|
||||
| 厂商推送 SDK | 需企业资质与逐厂商接入,侧载 APK 到达率差 |
|
||||
| 水印合成 | 样式必然反复调整,放 Web 侧 canvas 叠加 |
|
||||
| 图表、虚拟列表、图片压缩 | Web 层已够用,搬进原生只增加维护面 |
|
||||
| 扫描枪适配 | USB / 蓝牙 HID 即键盘输入,隐藏 input 即可 |
|
||||
|
||||
---
|
||||
|
||||
## 二、接口契约
|
||||
|
||||
所有方法失败时 `reject(message, code)`,`code` 取值见各节。成功时 `resolve` 的对象结构如下。
|
||||
|
||||
### 2.1 `getInfo()`
|
||||
|
||||
```ts
|
||||
{
|
||||
versionCode: number; // 壳 versionCode
|
||||
versionName: string; // 壳 versionName
|
||||
packageName: string;
|
||||
sdkInt: number;
|
||||
webViewVersion: string;
|
||||
capabilities: string[]; // 能力名数组,见下表
|
||||
}
|
||||
```
|
||||
|
||||
能力名与方法的对应关系:
|
||||
|
||||
```
|
||||
scan, capture, download, share, print,
|
||||
notify.schedule, notify.list, notify.permission, notify.exact,
|
||||
voice, biometric, session,
|
||||
btPrint, saf, calendar,
|
||||
app.state, app.network, app.permission, app.device,
|
||||
contacts, misc
|
||||
```
|
||||
|
||||
**前端必须以此数组判断能力是否存在**,不要用 `try/catch` 或猜测。
|
||||
|
||||
### 2.2 `scan(options?)`
|
||||
|
||||
```ts
|
||||
options: {
|
||||
formats?: string[]; // 默认 ["QR_CODE","CODE_128","CODE_39","EAN_13","EAN_8"]
|
||||
torch?: boolean; // 初始手电筒状态
|
||||
continuous?: boolean; // 连续扫码,识别成功不关闭页面
|
||||
}
|
||||
=> { text: string, format: string }
|
||||
```
|
||||
|
||||
- 整页原生取景,UI 只有返回、手电筒、相册、取景框,**不放业务文案**
|
||||
- `continuous` 为真时每次识别通过 `scanResult` 事件回传,页面不关闭,点返回时 resolve 最后一次结果
|
||||
- 相册识别走系统图片选择,单张解码
|
||||
|
||||
### 2.3 `capture(options?)`
|
||||
|
||||
```ts
|
||||
options: {
|
||||
multiple?: boolean; // 默认 false
|
||||
maxCount?: number; // 多张时的上限,默认 9
|
||||
facing?: "back" | "front";
|
||||
flash?: boolean;
|
||||
}
|
||||
=> { files: Array<{ path: string, name: string, size: number, mimeType: string }> }
|
||||
```
|
||||
|
||||
- `path` 是 `file://` 形式的 cache 路径,Web 侧需经 `Capacitor.convertFileSrc()` 使用
|
||||
- **不压缩、不加水印**,压缩交给现有 `src/utils/imageCompression.ts`
|
||||
|
||||
### 2.4 `download(options)`
|
||||
|
||||
```ts
|
||||
options: {
|
||||
url: string;
|
||||
fileName: string;
|
||||
subDir?: string; // 默认 GaoCustomer
|
||||
notify?: boolean; // 默认 true,通知栏显示进度
|
||||
}
|
||||
=> { uri: string, path: string, name: string, size: number }
|
||||
```
|
||||
|
||||
- 落 `Environment.DIRECTORY_DOWNLOADS/<subDir>/`,Android 10+ 免存储权限
|
||||
- `uri` 为 `content://`;`path` 是下载完成后复制到 cache 的 `file://` 地址,分享与打印用它
|
||||
(Downloads 里的文件不在 FileProvider 放行范围内)
|
||||
- 下载是异步的,Promise 在下载完成后 resolve;10 分钟未完成按超时 reject
|
||||
|
||||
### 2.5 `share(options)`
|
||||
|
||||
```ts
|
||||
options: { path: string, mimeType?: string, title?: string, text?: string }
|
||||
=> void
|
||||
```
|
||||
|
||||
### 2.6 `print(options)`
|
||||
|
||||
```ts
|
||||
options: { paths: string[], jobName?: string }
|
||||
=> void
|
||||
```
|
||||
|
||||
- 图片按 A4 等比缩放,一张一页
|
||||
- PDF 直接交给打印框架
|
||||
- **无法静默打印**,始终弹系统打印面板(系统限制)
|
||||
|
||||
### 2.7 `scheduleNotification(options)`
|
||||
|
||||
```ts
|
||||
options: {
|
||||
id?: number; // 不传则自增
|
||||
title: string;
|
||||
body: string;
|
||||
at: number; // epoch 毫秒,必须大于当前时间
|
||||
repeat?: "none" | "daily" | "weekly" | "yearly";
|
||||
route?: string; // 点击后跳转的路径,如 "/product/order-fulfillments?status=PENDING"
|
||||
channel?: "reminder" | "alert";
|
||||
owner?: string; // 归属标识,通常是登录用户 ID,用于共用设备隔离
|
||||
}
|
||||
=> { id: number, at: number }
|
||||
|
||||
cancelNotification({ id }) => { id }
|
||||
cancelAllNotifications({ owner? }) => void // 传 owner 只清该归属的任务
|
||||
|
||||
listScheduledNotifications({ owner? }) => {
|
||||
items: Array<{
|
||||
id: number, title: string, body: string,
|
||||
at: number, repeat: string,
|
||||
route: string | null, owner: string | null,
|
||||
channel: "reminder" | "alert"
|
||||
}>
|
||||
}
|
||||
```
|
||||
|
||||
- `reminder` 渠道为默认重要性,`alert` 为高重要性(响铃 + 震动)
|
||||
- 重复任务由接收器在触发时重新排程,不依赖 `setRepeating`
|
||||
- 设备重启后由 `BOOT_COMPLETED` 恢复全部未过期任务
|
||||
- 点击通知:冷启动与热启动都会把 `route` 交给 Web,见 2.8
|
||||
- **`listScheduledNotifications` 返回的是「原生记录过的任务」,不是 AlarmManager 的真实状态**:
|
||||
系统强停、省电策略清理闹钟后,这里仍然会列出任务。它用于诊断和账号隔离,
|
||||
不能当作「闹钟一定还在」的依据 —— 可靠做法是冷启动无条件全量重排(同 id 覆盖,天然幂等)
|
||||
|
||||
### 2.8 通知路由的两种消费方式
|
||||
|
||||
```ts
|
||||
// 冷启动:Web 起来后主动拉一次,取走即清除
|
||||
getLaunchRoute() => { route: string | null }
|
||||
|
||||
// 运行中:原生派发 window 事件
|
||||
window.addEventListener("nativekit:route", e => { ... }) // e.detail.route
|
||||
```
|
||||
|
||||
原生侧同时写 SharedPreferences 并 `triggerJSEvent`,两条路都能拿到。
|
||||
|
||||
### 2.9 语音
|
||||
|
||||
```ts
|
||||
voiceAvailable() => { channel: "recognizer" | "intent" | "none", engine?: string }
|
||||
|
||||
voiceStart(options?: {
|
||||
lang?: string; // 默认 zh-CN
|
||||
partial?: boolean; // 默认 true,回调中间结果
|
||||
preferOffline?: boolean;
|
||||
}) => { text: string, confidence?: number }
|
||||
|
||||
voiceStop() => void // 停止录音;最终结果仍由 voiceStart 的 Promise 返回
|
||||
voiceCancel() => void // 放弃本次识别,voiceStart 立即以 cancelled 拒绝
|
||||
```
|
||||
|
||||
事件:
|
||||
|
||||
```
|
||||
voicePartial { text: string }
|
||||
voiceState { state: "listening" | "processing" | "idle" }
|
||||
```
|
||||
|
||||
- 通道 A `SpeechRecognizer`:需要 `RECORD_AUDIO`,支持 partial
|
||||
- 通道 B `ACTION_RECOGNIZE_SPEECH`:不需要权限,覆盖无识别服务的 ROM,拿不到 partial
|
||||
- 两条通道都会在识别期间**置位内部导航标记**,避免被误判为「从后台回到前台」
|
||||
|
||||
### 2.10 生物识别与会话
|
||||
|
||||
```ts
|
||||
biometricAvailable() => { available: boolean, type: string } // type: fingerprint | face | iris | none
|
||||
biometricUnlock(options?: { title?: string, subtitle?: string, cancelText?: string }) => { ok: boolean }
|
||||
saveSession(options: { json: string }) => void
|
||||
readSession() => { json: string | null }
|
||||
clearSession() => void
|
||||
```
|
||||
|
||||
- 会话由 Android Keystore 的 AES/GCM 密钥加密后存 SharedPreferences,密钥不出 TEE
|
||||
- `readSession()` 不校验指纹,**指纹闸门由前端控制**:先 `biometricUnlock()` 成功再 `readSession()`
|
||||
- 若要更强约束,后续可加「会话读取必须带一次生物识别」的开关,接口预留
|
||||
|
||||
### 2.11 蓝牙打印
|
||||
|
||||
```ts
|
||||
listPrinters() => { printers: Array<{ name: string, address: string, bonded: boolean }> }
|
||||
|
||||
printRaw(options: {
|
||||
address: string;
|
||||
data: string; // base64 编码的 ESC/POS 字节流
|
||||
}) => { bytes: number }
|
||||
```
|
||||
|
||||
- `data` 由前端拼装,小票模板、中文位图渲染全部在前端完成
|
||||
- 原生只负责:连接 SPP、写入字节、关闭
|
||||
- 需要 `BLUETOOTH_CONNECT`(Android 12+ 运行时权限)
|
||||
- 已配对设备优先;未配对的设备需用户先在系统设置里配对
|
||||
|
||||
### 2.12 SAF
|
||||
|
||||
```ts
|
||||
pickFile(options?: { mimeTypes?: string[], multiple?: boolean })
|
||||
=> { files: Array<{ path: string, name: string, size: number, mimeType: string }> }
|
||||
|
||||
saveFile(options: { fileName: string, mimeType?: string, data: string }) // data 为 base64
|
||||
=> { path: string, name: string }
|
||||
```
|
||||
|
||||
- `pickFile` 选中后把内容拷到 `cacheDir/nativekit-pick/`,返回 `file://`
|
||||
原因:`content://` 在 WebView 的 `fetch()` 里不可读
|
||||
- `saveFile` 走 `ACTION_CREATE_DOCUMENT`,由用户选择落点
|
||||
|
||||
### 2.13 系统日历
|
||||
|
||||
```ts
|
||||
calendarAvailable() => {
|
||||
canInsert: boolean; // 设备上有能接收 INSERT 的日历应用
|
||||
canWriteSilent: boolean; // 已授权且有可写日历,可静默写入
|
||||
calendars: Array<{ id: string, name: string, accountName: string, accountType: string, primary: boolean }>
|
||||
}
|
||||
|
||||
addCalendarEvent(options: {
|
||||
title: string;
|
||||
beginAt: number; // epoch 毫秒
|
||||
endAt?: number; // 不传默认 beginAt + 30 分钟
|
||||
description?: string;
|
||||
location?: string;
|
||||
allDay?: boolean;
|
||||
reminderMinutes?: number[]; // 提前多少分钟提醒,默认 [0] 即事件开始时
|
||||
calendarId?: string; // 不传按「主日历 > 本地日历 > 第一个」选
|
||||
mode?: "auto" | "silent" | "intent";
|
||||
}) => { mode: "silent" | "intent", eventId: string | null }
|
||||
|
||||
removeCalendarEvent(options: { eventId: string }) => { deleted: boolean }
|
||||
```
|
||||
|
||||
- **提醒事项做不到**:各家的备忘录/待办是私有数据库,没有标准 ContentProvider,也没有统一 Intent
|
||||
- `silent`:需要 `READ_CALENDAR` / `WRITE_CALENDAR`,且存在可写日历,返回 `eventId`
|
||||
- `intent`:不需要任何权限,拉起系统日历新建页,由用户确认,**拿不到 `eventId`,后续无法删除**
|
||||
- `auto`:先试静默,没权限或没有可写日历时自动降级到 intent
|
||||
- 全天事件:`allDay: true` 时 `beginAt` / `endAt` 必须是 **UTC 午夜**的毫秒值,否则整体偏移一天
|
||||
- 写入后提醒由系统日历应用负责,与 `scheduleNotification` 是两套互补机制
|
||||
|
||||
### 2.14 前后台与网络
|
||||
|
||||
```ts
|
||||
getAppState() => { isActive: boolean }
|
||||
|
||||
getNetworkStatus() => { connected: boolean, type: "wifi" | "cellular" | "ethernet" | "vpn" | "other" | "none" }
|
||||
|
||||
// 事件
|
||||
appStateChange { isActive: boolean }
|
||||
networkStatusChange { connected: boolean, type: string }
|
||||
```
|
||||
|
||||
- 前台判定用**进程内 Activity 计数**,不是 `onResume/onPause`:打开扫码页、语音页、SAF 选择器都会让 MainActivity pause,用后者会被误判成切到后台
|
||||
- 计数归零时用进程 importance 兜底:`restartApp` 重建后新插件实例注册回调晚于新 Activity 的 onStart,只靠计数会一直误报后台
|
||||
- `networkStatusChange` 只在真正变化时派发,网络抖动不会刷屏
|
||||
- 冷启动时事件可能早于 Web 就绪,前端应先用 `getAppState()` / `getNetworkStatus()` 拉一次基线
|
||||
|
||||
### 2.15 权限状态与系统设置
|
||||
|
||||
```ts
|
||||
getPermissionStates() => {
|
||||
camera: "granted" | "denied" | "prompt" | "prompt-with-rationale",
|
||||
microphone: 同上,
|
||||
calendar: 同上,
|
||||
contacts: 同上,
|
||||
bluetooth: 同上, // Android 12 以下恒为 granted
|
||||
notifications: "granted" | "denied" // Android 13 以下取系统开关状态
|
||||
}
|
||||
|
||||
openAppSettings() => void // 应用详情页,权限被「拒绝且不再询问」后唯一的补救入口
|
||||
openNotificationSettings() => void
|
||||
openBatteryOptimizationSettings() => void // 直接把本应用加入电池白名单;ROM 不认时退回列表页
|
||||
isIgnoringBatteryOptimizations() => { ignoring: boolean }
|
||||
```
|
||||
|
||||
- `prompt` 表示还没问过、可以再弹;`denied` 表示已经拒绝,再调权限 API 不会弹窗,只能引导去设置
|
||||
- 本地通知能否可靠触发,前提是 `isIgnoringBatteryOptimizations()` 为真
|
||||
|
||||
### 2.16 设备控制
|
||||
|
||||
```ts
|
||||
getDeviceId() => { androidId: string } // Android 8+ 按签名隔离,清数据/重装不变
|
||||
getRingerMode() => { mode: "silent" | "vibrate" | "normal" }
|
||||
setKeepAwake({ enabled: boolean }) => { enabled: boolean }
|
||||
setOrientation({ orientation: "portrait" | "landscape" | "auto" }) => { orientation: string }
|
||||
restartApp() => void // 清空任务栈重建 Activity,进程不换
|
||||
clearWebCache({ storage?: boolean }) => void
|
||||
```
|
||||
|
||||
- `setKeepAwake` 只作用于当前 Activity,离开页面必须关掉,否则一直亮屏耗电
|
||||
- `restartApp` **不是杀进程**:Android 10 起禁止后台启动 Activity,靠 `AlarmManager` 把进程拉回来的做法实测会被系统拦掉,杀了就再也起不来。这里改成清空任务栈重建 MainActivity,进程不变但 WebView 重新加载、Bridge 重建,对「切账号彻底重置」够用
|
||||
- `clearWebCache` 的 `storage: true` 会连 localStorage 和 Cookie 一起清,**登录态、主题、热更记录都会没**,只用于排查白屏或切账号彻底重置
|
||||
|
||||
### 2.17 通讯录
|
||||
|
||||
```ts
|
||||
contactsAvailable() => { canWrite: boolean, hasPermission: boolean, total: number }
|
||||
|
||||
addContact({ name, phone, note?, businessId?, groupTag? }) => { rawContactId: number }
|
||||
|
||||
syncContacts({
|
||||
items: Array<{ id: string, name: string, phone: string, note?: string }>,
|
||||
groupTag?: string // 默认 GaoCustomer,用于区分批次
|
||||
}) => { inserted: number, updated: number, deleted: number, total: number }
|
||||
|
||||
clearContacts({ groupTag? }) => { deleted: number }
|
||||
```
|
||||
|
||||
- `syncContacts` 是**批量幂等**的:以 `id` 为准做差集,缺的插入、变了的更新、多出来的删除。同一个 `groupTag` 下不会残留脏号码
|
||||
- 业务 ID 存在自定义 MIMETYPE 的 Data 行里,**通讯录界面不会显示**,也不占姓名/备注/昵称任何可见字段
|
||||
- 不会自动加任何姓名后缀,显示名完全由前端传
|
||||
- 每批 100 条执行一次 `applyBatch`,500 个客户约 1–2 秒
|
||||
- 写入后系统语音助手("打电话给张三")和来电识别才能命中;业务数据助手仍然读不到
|
||||
|
||||
### 2.18 杂项
|
||||
|
||||
```ts
|
||||
vibrate(options?: { ms?: number }) => void
|
||||
copy(options: { text: string }) => void
|
||||
getDeviceInfo() => {
|
||||
brand: string, model: string, manufacturer: string,
|
||||
sdkInt: number, webViewVersion: string,
|
||||
packageName: string, versionCode: number, versionName: string
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、权限与清单变更
|
||||
|
||||
`AndroidManifest.xml` 一次性声明,**后续加权限必然要重新发壳**。
|
||||
|
||||
| 权限 | 用途 | 授予方式 |
|
||||
|---|---|---|
|
||||
| `CAMERA` | 扫码、拍照 | 已在,运行时 |
|
||||
| `RECORD_AUDIO` | 语音输入通道 A | 新增,运行时 |
|
||||
| `POST_NOTIFICATIONS` | 本地通知(33+) | 新增,运行时 |
|
||||
| `READ_MEDIA_IMAGES` / `READ_MEDIA_VIDEO` | 相册识别、选图(33+) | 新增,运行时 |
|
||||
| `READ_EXTERNAL_STORAGE` | 同上,`maxSdkVersion=32` | 新增,运行时 |
|
||||
| `BLUETOOTH_CONNECT` | 蓝牙打印(31+) | 新增,运行时 |
|
||||
| `BLUETOOTH_SCAN` | 扫描未配对打印机(31+) | 新增,运行时,`usesPermissionFlags="neverForLocation"` |
|
||||
| `BLUETOOTH` / `BLUETOOTH_ADMIN` | 同上,`maxSdkVersion=30` | 新增 |
|
||||
| `READ_CALENDAR` / `WRITE_CALENDAR` | 写入系统日历日程 | 新增,运行时 |
|
||||
| `READ_CONTACTS` / `WRITE_CONTACTS` | 批量写入客户通讯录 | 新增,运行时 |
|
||||
| `FOREGROUND_SERVICE` | 预留常驻能力 | 新增 |
|
||||
| `WAKE_LOCK` | 定时通知唤醒 | 新增 |
|
||||
| `RECEIVE_BOOT_COMPLETED` | 重启恢复定时任务 | 新增 |
|
||||
| `SCHEDULE_EXACT_ALARM` | 精确闹钟(32+) | 新增,用户手动授予 |
|
||||
| `VIBRATE` | 震动反馈 | 新增 |
|
||||
| `ACCESS_NETWORK_STATE` | DownloadManager | 新增 |
|
||||
| `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` | 引导加入后台白名单 | 新增,需引导页 |
|
||||
| `REQUEST_INSTALL_PACKAGES` | 壳自升级 | 已有 |
|
||||
| `INTERNET` | 网络 | 已有 |
|
||||
|
||||
`file_paths.xml` 同步收窄:原先的 `external-path path="."` 把整个外部存储暴露给 FileProvider,改为只放行 cache 与 app 私有目录。`ShellUpdater` 使用 `cacheDir/shell-updates`,不受影响。
|
||||
|
||||
---
|
||||
|
||||
## 四、依赖与体积
|
||||
|
||||
| 依赖 | 版本 | 用途 | 体积 |
|
||||
|---|---|---|---|
|
||||
| `androidx.camera:camera-core/camera2/lifecycle/view` | 1.4.2 | 预览、分析、拍照 | ~1.5MB |
|
||||
| `com.google.zxing:core` | 3.5.3 | 条码解码 | ~0.5MB |
|
||||
| `androidx.biometric:biometric` | 1.1.0 | 指纹 / 面容 | ~0.3MB |
|
||||
|
||||
不引入 `zxing-android-embedded`(自带一套 UI,与自定义取景冲突)。
|
||||
不引入 `androidx.security:security-crypto`(长期 alpha 且部分机型 MasterKey 创建失败),改为直接用 Android Keystore + AES/GCM 自实现,约 80 行。
|
||||
|
||||
`minifyEnabled` 本次仍保持 `false`。R8 会混淆 `@CapacitorPlugin` 注解类,预埋阶段先保证能跑通,等能力验证完再单独开一次。
|
||||
|
||||
---
|
||||
|
||||
## 五、前端约定
|
||||
|
||||
### 5.1 能力协商必须集中
|
||||
|
||||
新增 `src/utils/nativeCapabilities.ts`,**唯一入口**:
|
||||
|
||||
```ts
|
||||
const capabilities = ref<Set<string>>(new Set());
|
||||
export async function loadCapabilities(): Promise<void>; // 启动时调一次
|
||||
export function hasCapability(name: string): boolean;
|
||||
export function requireCapability(name: string): void; // 缺失时抛明确错误
|
||||
```
|
||||
|
||||
禁止在页面里散落 `Capacitor.isPluginAvailable()`。老壳上所有新能力都应「按钮不出现」,而不是「点了没反应」。
|
||||
|
||||
### 5.2 自测入口
|
||||
|
||||
设置页连点 5 次开启(复用 `createVConsoleClickHandler`),页面列出全部能力,逐项可手动触发。
|
||||
|
||||
**这一步不能省**:预埋的代码从不执行等于没测过,等半年后真要用时才发现问题,还是得开壳。
|
||||
|
||||
自测页是纯 Web,热更可改,不增加壳的维护面。
|
||||
|
||||
### 5.3 新能力上线的三段式
|
||||
|
||||
```
|
||||
1. 发壳(code 4)→ 通道切回 BUNDLE
|
||||
2. 推装机,确认设备都升到 4
|
||||
3. Gitea 改 APP_MIN_VERSION_CODE = 4
|
||||
4. 发首个使用新能力的热更包
|
||||
```
|
||||
|
||||
第 3 步不可逆:做了之后 `versionCode < 4` 的设备永久停在当前 BUNDLE,收不到任何后续修复。
|
||||
|
||||
---
|
||||
|
||||
## 六、实施步骤
|
||||
|
||||
| 阶段 | 内容 | 验收 |
|
||||
|---|---|---|
|
||||
| 一 | 依赖、权限、Manifest、`file_paths` 收窄、versionCode 4 | `assembleDebug` 通过,装上不崩 |
|
||||
| 二 | `NativeKit` 主类 + `getInfo()` + 全部方法骨架 | 能力表可读,未实现方法返回明确错误 |
|
||||
| 三 | 相机管线(扫码 + 拍照) | 真机扫码 8 个调用点场景可用,弱光与远景优于 JS 版 |
|
||||
| 四 | 下载、分享、打印、SAF | 导出 ZIP 落 Downloads,能分享到微信,能打二维码 |
|
||||
| 五 | 通知、语音 | 定时通知准点触发,重启后仍有效;语音在无 GMS 设备上自动降级 |
|
||||
| 六 | 生物识别、蓝牙打印、杂项 | 指纹解锁可用,58mm 小票机能出字 |
|
||||
| 七 | 自测页(Web 侧) | 全部能力逐项通过 |
|
||||
|
||||
每阶段单独打包装机验证,不要攒到最后一起验。
|
||||
|
||||
---
|
||||
|
||||
## 七、风险清单
|
||||
|
||||
| 风险 | 影响 | 处置 |
|
||||
|---|---|---|
|
||||
| 国产 ROM 无 `RecognitionService` | 语音不可用 | 双通道 + `voiceAvailable()` 探测,页面按结果渲染 |
|
||||
| Android 15 前台服务 `dataSync` 每日 6 小时上限 | 常驻失效 | 本次不做常驻;定时任务走 AlarmManager + BOOT_COMPLETED |
|
||||
| 精确闹钟未授权 | 提醒延迟 | `canScheduleExactAlarms()` 检查,未授权时降级 `setAndAllowWhileIdle` 并提供设置入口 |
|
||||
| 蓝牙 MAC 在无权限时不可读 | 打印机选不中 | `listPrinters()` 在申请 `BLUETOOTH_CONNECT` 后再调用 |
|
||||
| 国产 ROM 没有本地日历账户 | 静默写入无日历可选 | `auto` 模式降级到 `ACTION_INSERT`;前端先看 `calendarAvailable().canWriteSilent` |
|
||||
| 廉价热敏机无中文字库 | 小票乱码 | 前端优先试 GBK 直发,失败走位图点阵(384 点宽) |
|
||||
| WebView 内核过旧(Android 10 设备) | CameraX 无关,但 `:has()` 等 CSS 退化 | 原生扫码正好绕开 WebView 差异 |
|
||||
| 抬基线过早 | 未升级设备断流 | 严格按 5.3 顺序,第 3 步留缓冲期 |
|
||||
| 能力表与实现漂移 | 前端判存在但实际不可用 | `getInfo()` 的能力数组由代码常量生成,不手写 |
|
||||
|
||||
---
|
||||
|
||||
## 八、与壳升级流程的衔接
|
||||
|
||||
本次属于「新增插件 + 新增权限 + 新增 Activity」的完整原生变更,必须走 `NATIVE_UPGRADE.md` 全套流程:
|
||||
|
||||
1. `versionCode` 改成 4,`versionName` 改成 1.2.0
|
||||
2. `pnpm run android:sync:prod`
|
||||
3. `pnpm run android:apk`
|
||||
4. 核对 versionCode、`apksigner` 证书指纹(`3E:9C:CC:8A:…`)、包内不含内网地址
|
||||
5. 发 `kind = NATIVE` 发布记录
|
||||
6. **把通道切回最新 BUNDLE 记录**(不切则新壳 `check` 返回 null,热更断流)
|
||||
7. 装机确认后再抬 `APP_MIN_VERSION_CODE`
|
||||
|
||||
---
|
||||
|
||||
## 九、真机验证记录(2026-11-20)
|
||||
|
||||
设备:华为 SEA-AL10,Android 10(SDK 29),WebView 114.0.5735.196,无 GMS。
|
||||
|
||||
### 已验证通过
|
||||
|
||||
| 能力 | 验证方式与结果 |
|
||||
|---|---|
|
||||
| `getInfo` | 16 项能力全部返回,versionCode 4 / 1.2.0 |
|
||||
| `getDeviceInfo` | 机型、SDK、WebView 版本、包版本均正确 |
|
||||
| 通知排程 | 6 秒后精确触发,通知栏出现(自定义 `ic_notification` 图标、标题正文正确) |
|
||||
| 通知路由 | `am start --es nativekit_route` 等价路径,`getLaunchRoute` 首次取值、二次为 null |
|
||||
| 重复任务 | daily 任务触发后自动重排,间隔精确 86400000ms |
|
||||
| 任务列表 | `listScheduledNotifications` 返回 id/title/at/repeat/route/owner/channel,按 owner 过滤生效 |
|
||||
| 日历探测 | 华为本地日历 `com.android.huawei.phone` 可写,`canWriteSilent: true` |
|
||||
| 日历写入 | 静默写入成功,`content query` 核对到 `hasAlarm=1`,Reminders `minutes=0 / method=1` |
|
||||
| 日历删除 | `removeCalendarEvent` 后数据库记录消失 |
|
||||
| 语音 | `channel: "recognizer"`,华为系统识别引擎可用 |
|
||||
| 生物识别 | 硬件存在、未录指纹时正确返回 `none_enrolled` |
|
||||
| 会话加密 | Keystore AES/GCM 写入→读取一致,清除后为 null |
|
||||
| 下载器 | DownloadManager 落 Downloads,复制到 cache,`path` 可读 |
|
||||
| 扫码页 | CameraX 预览正常、取景框/手电筒/相册按钮齐全,无黑屏 |
|
||||
| 相册识别 | 选中 PNG 后正确解出 `GAO-NATIVE-TEST-2026` / `QR_CODE`,页面自动关闭 |
|
||||
| 拍照 | 预览正常、计数递增、多张模式可继续、返回 9MB 原图 |
|
||||
| 分享 | 系统面板弹出,缩略图正常,微信/邮件/文件管理可点 |
|
||||
| 打印 | A4 预览、二维码居中清晰、1/1 页 |
|
||||
| SAF 另存 | 写入 `content://`,`cat` 校验内容为 `hello native` |
|
||||
| 震动 / 剪贴板 | 均返回成功 |
|
||||
|
||||
### 未覆盖(受设备条件限制)
|
||||
|
||||
| 项 | 原因 |
|
||||
|---|---|
|
||||
| 实时摄像头扫码解码 | 需要实物二维码对准镜头,无法自动化;YUV 旋转分支是唯一未跑到的代码路径 |
|
||||
| 蓝牙 ESC/POS 打印 | 无配对打印机,`listPrinters` 只验证了空列表分支 |
|
||||
| 生物识别解锁 | 设备未录入指纹 |
|
||||
| 通知点击的真实 UI 点击 | 用 `am start` 模拟了同一 Intent 路径,PendingIntent 本身未点 |
|
||||
|
||||
### 真机测出并已修复的两个问题
|
||||
|
||||
| 问题 | 现象 | 修复 |
|
||||
|---|---|---|
|
||||
| `route` 脏值 | `optString` 对 JSON null 返回字符串 `"null"`,重排时又原样写回,点通知会跳到 `/null` | 读取判 `isNull` + `cleanText` 清洗空串与 `"null"`;写入前也归一 |
|
||||
| 分区存储 | Android 10 上按绝对路径读 Downloads 里的文件失败,`path` 恒为空 | 改用 `DownloadManager.openDownloadedFile()` 拿 fd 复制 |
|
||||
|
||||
两个都是编译期看不出来、只能装机才暴露的问题。
|
||||
|
||||
## 十、第二批能力实测(2026-11-20)
|
||||
|
||||
同一台华为 SEA-AL10 / Android 10。
|
||||
|
||||
| 能力 | 结果 |
|
||||
|---|---|
|
||||
| `getPermissionStates` | 6 项权限状态全部正确返回 |
|
||||
| `getNetworkStatus` | `wifi` / 关闭 WiFi 后 `none` → `cellular` → 恢复 `wifi` |
|
||||
| `appStateChange` | 按 HOME 收到 `{isActive:false}`,回前台收到 `{isActive:true}` |
|
||||
| `networkStatusChange` | 关开 WiFi 的两次变化都收到,无重复派发 |
|
||||
| `getDeviceId` | 返回稳定 `ANDROID_ID` |
|
||||
| `getRingerMode` | 设备静音时返回 `silent` |
|
||||
| `isIgnoringBatteryOptimizations` | 未加白名单时 `false` |
|
||||
| `setKeepAwake` / `setOrientation` | 横屏锁定后 `mCurrentRotation=ROTATION_90`,恢复 `auto` 正常 |
|
||||
| `openAppSettings` | 跳到 `com.android.settings/.applications.InstalledAppDetails` |
|
||||
| `clearWebCache` | 只清 HTTP 缓存时返回 ok |
|
||||
| `syncContacts` 首次 | `inserted=3`,系统 `content query` 核对到姓名与号码 |
|
||||
| `syncContacts` 二次 | 改 1、删 1、加 1,返回 `inserted=1 / updated=2 / deleted=1`,数据库核对无残留 |
|
||||
| `clearContacts` | `deleted=3`,之后 `No result found` |
|
||||
| `restartApp` | 进程 PID 不变,Activity 重建,21 项能力与 WebView 均恢复 |
|
||||
|
||||
### 本轮测出并修复的三个问题
|
||||
|
||||
| 问题 | 现象 | 修复 |
|
||||
|---|---|---|
|
||||
| `restartApp` 起不来 | 杀进程后 `AlarmManager` 的 PendingIntent 被 Android 10 的后台启动限制拦掉,7 秒后仍停在桌面 | 改为清空任务栈重建 Activity,不杀进程 |
|
||||
| 重建后 `isActive` 恒为 false | 新插件实例注册回调晚于新 Activity 的 onStart,且旧 Activity 的 stop 被新实例接收 | 初始计数记 1 + 首次 started 只做对齐 + 归零时用进程 importance 兜底 |
|
||||
| RawContact 插入不稳 | 不写 `ACCOUNT_TYPE` / `ACCOUNT_NAME` 时部分 ROM 行为不一致 | 显式写 null,明确落到本地联系人 |
|
||||
|
||||
## 十一、登录态联调(2026-11-20)
|
||||
|
||||
后端 `http://192.168.11.7:18091`,账号 `Admin`,WebView 114,设备同前。
|
||||
|
||||
### 接入时踩到的两个接口约定
|
||||
|
||||
| 接口 | 约束 | 踩坑表现 |
|
||||
|---|---|---|
|
||||
| `GET /captcha` | 必须带 `width` 与 `height` | 不带参数返回 `50000 not found width or less than 64` |
|
||||
| `POST /gao/customer/follow-up-reminder/create` | `remindAt` 必须是整分钟(秒、毫秒为 0) | 否则返回 `提醒时间必须精确到分钟`,需要用 `Math.ceil(ts / 60000) * 60000` 处理 |
|
||||
|
||||
### 真实数据下的端到端验证
|
||||
|
||||
| 环节 | 结果 |
|
||||
|---|---|
|
||||
| 登录 | `POST /user/login` 返回 token 与 user,写入 `gao-customer-h5:user` 后重载进入 `/customers` |
|
||||
| 客户列表 | 354 条,前 50 条中 33 条有 `telephone` |
|
||||
| 批量写通讯录 | 取前 10 条真实客户,`inserted=10`,系统 `content query` 核对姓名与号码一致 |
|
||||
| 创建跟进提醒 | `remindAt` 取整分钟后创建成功,回读 id 与时间正确 |
|
||||
| 映射到原生 | 提醒 id 哈希成通知 id,`owner` 用登录用户 id,`route` 拼客户详情,排程成功 |
|
||||
| 通知触发 | 15 秒后弹出,`id / title / channel=nativekit_alert` 全部正确 |
|
||||
| 写日历 | 静默写入成功,`_id=262`、`title=跟进 陈小花`、`hasAlarm=1` |
|
||||
| 清理 | 删除提醒、取消通知、删除日历、`clearContacts` 删除 10 条;两处 `content query` 均返回 `No result found` |
|
||||
|
||||
**结论:从业务数据到原生通知与日历的完整链路可用**,前端接入时只需要决定同步策略与 id 映射算法。
|
||||
@@ -40,15 +40,22 @@ grep versionCode android/app/build.gradle
|
||||
|
||||
- 增删插件后执行 `pnpm exec cap sync android`
|
||||
- 确认 `capacitor.config.ts` 无遗漏
|
||||
- **`minSdkVersion` 已是 29(Android 10+)**:下一次发壳,Android 9 及以下的机器装不上,
|
||||
会永久停在旧版本。发之前先确认设备分布,别把一个还在用老系统的门店锁死
|
||||
- **打壳前先 `pnpm run android:sync:prod` 重建资源**:它用 `.env.production` 构建并会清掉
|
||||
残留的 `VITE_API_BASE_URL`。真机调试用的 `android:sync:dev`(或 `android:open`)会把局域网地址
|
||||
写进 `dist` 和 `android/app/src/main/assets/public`,直接拿去打包就会打出一个连内网的正式包
|
||||
- 打完核对:`aapt2 dump badging` 的 versionCode、`apksigner verify --print-certs` 的证书,
|
||||
以及解包 grep 接口地址(内网地址必须为 0 次)
|
||||
- 用 Android Studio 打包,**签名必须与线上包一致**:线上 1.0.0 用的是
|
||||
`twa/android.keystore`(alias `gao-customer`,证书 `CN=yeyu` / SHA-256 `3E:9C:CC:8A:…`)。
|
||||
签名不一致时系统会拒绝覆盖安装,老用户只能卸载重装
|
||||
- `pnpm run android:apk` 走的是 `assembleDebug`,签的是本机 debug key,**不能用于发版**
|
||||
- **一条命令出正式包**:`pnpm run android:apk`
|
||||
= `android:sync:prod` + `assembleRelease` + 用根目录 `android.keystore` 签名 + 复制到
|
||||
`android/app/release/app-release.apk`(已 gitignore),末尾会打印 versionCode、大小、
|
||||
sha256 和证书指纹
|
||||
- 签名凭证放在 `android/keystore.properties`(已 gitignore),格式见同目录
|
||||
`keystore.properties.example`;缺密码时脚本会直接拦住,不会产出 debug 包
|
||||
- 只重新打包、不重建 web:`pnpm run android:apk -- -SkipSync`
|
||||
- 仍然可以用 Android Studio 打包,但**签名必须是根目录 `android.keystore`**
|
||||
(alias `gao-customer`,`CN=yeyu` / SHA-256 `3E:9C:CC:8A:…`),否则系统拒绝覆盖安装
|
||||
|
||||
### 3. 提高 CI 的兼容基线
|
||||
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
// 发版签名凭证放在 android/keystore.properties(已 gitignore),不进版本库。
|
||||
// 缺失时 assembleRelease 会产出未签名包,脚本会拦住并提示补全。
|
||||
def keystorePropertiesFile = rootProject.file("keystore.properties")
|
||||
def keystoreProperties = new Properties()
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystorePropertiesFile.withInputStream { keystoreProperties.load(it) }
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.imyeyu.gao.customer"
|
||||
compileSdk = rootProject.ext.compileSdkVersion
|
||||
@@ -7,8 +15,8 @@ android {
|
||||
applicationId "com.imyeyu.gao.customer"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 3
|
||||
versionName "1.1.0"
|
||||
versionCode 4
|
||||
versionName "1.2.0"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
@@ -16,12 +24,30 @@ android {
|
||||
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
||||
}
|
||||
}
|
||||
signingConfigs {
|
||||
release {
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
storeFile rootProject.file(keystoreProperties['storeFile'])
|
||||
storePassword keystoreProperties['storePassword']
|
||||
keyAlias keystoreProperties['keyAlias']
|
||||
keyPassword keystoreProperties['keyPassword']
|
||||
}
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
signingConfig signingConfigs.release
|
||||
}
|
||||
}
|
||||
}
|
||||
// 与 capacitor-android 保持一致,避免 JVM target 不一致的编译告警
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_21
|
||||
targetCompatibility JavaVersion.VERSION_21
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
@@ -36,6 +62,17 @@ dependencies {
|
||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||
implementation project(':capacitor-android')
|
||||
|
||||
// 相机管线:扫码与拍照共用,避免 WebView getImageCapture 的差异与掉帧
|
||||
implementation "androidx.camera:camera-core:$androidxCameraVersion"
|
||||
implementation "androidx.camera:camera-camera2:$androidxCameraVersion"
|
||||
implementation "androidx.camera:camera-lifecycle:$androidxCameraVersion"
|
||||
implementation "androidx.camera:camera-view:$androidxCameraVersion"
|
||||
// 纯 JVM 解码库,不依赖 Google Play 服务
|
||||
implementation "com.google.zxing:core:$zxingVersion"
|
||||
// 指纹 / 面容解锁
|
||||
implementation "androidx.biometric:biometric:$androidxBiometricVersion"
|
||||
|
||||
testImplementation "junit:junit:$junitVersion"
|
||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
||||
|
||||
@@ -24,6 +24,30 @@
|
||||
|
||||
</activity>
|
||||
|
||||
<!-- 扫码与拍照共用的相机页,不接受外部调用 -->
|
||||
<activity
|
||||
android:name=".nativekit.CameraKitActivity"
|
||||
android:exported="false"
|
||||
android:theme="@style/AppTheme.CameraKit"
|
||||
android:launchMode="singleTop"
|
||||
android:configChanges="orientation|screenSize|keyboardHidden|screenLayout|smallestScreenSize|uiMode" />
|
||||
|
||||
<!-- 定时通知触发;由 AlarmManager 发出,不对外 -->
|
||||
<receiver
|
||||
android:name=".nativekit.NotificationAlarmReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- 重启与覆盖安装后恢复未过期的定时通知 -->
|
||||
<receiver
|
||||
android:name=".nativekit.BootReceiver"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
@@ -35,10 +59,68 @@
|
||||
</provider>
|
||||
</application>
|
||||
|
||||
<!--
|
||||
Android 11 起受包可见性限制,不声明 queries 时 resolveActivity 与
|
||||
SpeechRecognizer.isRecognitionAvailable 都会误判为「无可用识别服务」。
|
||||
日历那条用于判断设备上是否存在能接收 INSERT 的日历应用。
|
||||
-->
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.speech.RecognitionService" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.speech.action.RECOGNIZE_SPEECH" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.INSERT" />
|
||||
<data android:mimeType="vnd.android.cursor.dir/event" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<!-- Permissions -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
|
||||
<!-- 语音输入:仅识别器通道需要,Intent 通道不需要 -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
|
||||
<!-- 本地通知与定时调度 -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
|
||||
<!-- 相册选择与条码图片识别 -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
|
||||
<!-- 写入系统日历:跟进提醒同步为日程事件 -->
|
||||
<uses-permission android:name="android.permission.READ_CALENDAR" />
|
||||
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
|
||||
|
||||
<!-- 写入通讯录:让系统语音助手与来电识别能拿到客户姓名号码 -->
|
||||
<uses-permission android:name="android.permission.READ_CONTACTS" />
|
||||
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
|
||||
|
||||
<!-- 蓝牙小票与标签打印 -->
|
||||
<uses-permission
|
||||
android:name="android.permission.BLUETOOTH"
|
||||
android:maxSdkVersion="30" />
|
||||
<uses-permission
|
||||
android:name="android.permission.BLUETOOTH_ADMIN"
|
||||
android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission
|
||||
android:name="android.permission.BLUETOOTH_SCAN"
|
||||
android:usesPermissionFlags="neverForLocation" />
|
||||
</manifest>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.imyeyu.gao.customer;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.graphics.Color;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.SystemClock;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
@@ -13,15 +15,42 @@ import androidx.core.graphics.Insets;
|
||||
import androidx.core.view.ViewCompat;
|
||||
import androidx.core.view.WindowCompat;
|
||||
import androidx.core.view.WindowInsetsCompat;
|
||||
import com.getcapacitor.Bridge;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
import com.imyeyu.gao.customer.mediasaver.MediaSaverPlugin;
|
||||
import com.imyeyu.gao.customer.nativekit.NativeKitPlugin;
|
||||
import com.imyeyu.gao.customer.nativekit.NotificationScheduler;
|
||||
import com.imyeyu.gao.customer.shellupdater.ShellUpdaterPlugin;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
|
||||
/**
|
||||
* 内部导航标记。
|
||||
*
|
||||
* 语音 Intent 通道会压一层 Activity,返回时触发 onResume;将来接入 appStateChange 后
|
||||
* 需要用它把「从系统语音页返回」和「真正的回到前台」区分开,否则会误触发数据刷新。
|
||||
*/
|
||||
private static long internalNavigationAt = 0L;
|
||||
|
||||
public static void markInternalNavigation() {
|
||||
internalNavigationAt = SystemClock.elapsedRealtime();
|
||||
}
|
||||
|
||||
public static boolean consumeInternalNavigation() {
|
||||
boolean recent = 0L < internalNavigationAt
|
||||
&& SystemClock.elapsedRealtime() - internalNavigationAt < 8000L;
|
||||
internalNavigationAt = 0L;
|
||||
return recent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
registerPlugin(ShellUpdaterPlugin.class);
|
||||
registerPlugin(MediaSaverPlugin.class);
|
||||
registerPlugin(NativeKitPlugin.class);
|
||||
super.onCreate(savedInstanceState);
|
||||
applyEdgeToEdge();
|
||||
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
|
||||
@@ -41,6 +70,53 @@ public class MainActivity extends BridgeActivity {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知点击与外部跳转的统一入口。
|
||||
*
|
||||
* Capacitor 的 BridgeActivity 在 load() 里会调一次 onNewIntent(getIntent()),
|
||||
* 所以冷启动与热启动都会走到这里,不需要在 onCreate 里重复处理。
|
||||
*/
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
setIntent(intent);
|
||||
handleNotificationRoute(intent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把通知带来的路由交给 Web。
|
||||
*
|
||||
* 两条路都走:写 SharedPreferences 供冷启动后主动拉取,同时派发 window 事件供运行中响应。
|
||||
* 只派发事件的话,WebView 还没加载完时点通知会丢;只写存储的话,前台时点通知没反应。
|
||||
*/
|
||||
private void handleNotificationRoute(Intent intent) {
|
||||
if (intent == null) {
|
||||
return;
|
||||
}
|
||||
String route = intent.getStringExtra(NotificationScheduler.EXTRA_ROUTE);
|
||||
if (route == null || route.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
intent.removeExtra(NotificationScheduler.EXTRA_ROUTE);
|
||||
|
||||
getSharedPreferences(NativeKitPlugin.PREFS, MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString(NativeKitPlugin.KEY_LAUNCH_ROUTE, route)
|
||||
.apply();
|
||||
|
||||
Bridge bridge = getBridge();
|
||||
if (bridge == null) {
|
||||
return;
|
||||
}
|
||||
JSONObject detail = new JSONObject();
|
||||
try {
|
||||
detail.put("route", route);
|
||||
} catch (Exception ignored) {
|
||||
return;
|
||||
}
|
||||
bridge.triggerWindowJSEvent("nativekit:route", detail.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 让窗口真正 edge-to-edge,安全区由 Web 侧按 --tui-safe-* 补齐。
|
||||
*
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package com.imyeyu.gao.customer.mediasaver;
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.ContentValues;
|
||||
import android.net.Uri;
|
||||
import android.os.Environment;
|
||||
import android.provider.MediaStore;
|
||||
import android.util.Base64;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.getcapacitor.PluginMethod;
|
||||
import com.getcapacitor.annotation.CapacitorPlugin;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/// 把网页里拍到的照片/视频写进系统相册
|
||||
///
|
||||
/// 走 MediaStore 的 IS_PENDING 流程,Android 10 起不需要任何存储权限。
|
||||
/// 分块接收是为了避免大视频在 JS 与原生之间一次性复制导致内存翻倍。
|
||||
@CapacitorPlugin(name = "MediaSaver")
|
||||
public class MediaSaverPlugin extends Plugin {
|
||||
|
||||
/// 单个文件上限,防止异常调用把手机存储写满
|
||||
private static final long MAX_BYTES = 512L * 1024 * 1024;
|
||||
|
||||
private final ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
private final Map<String, Session> sessions = new ConcurrentHashMap<>();
|
||||
|
||||
private static class Session {
|
||||
final File temp;
|
||||
final String fileName;
|
||||
final String mimeType;
|
||||
final boolean video;
|
||||
long size;
|
||||
|
||||
Session(File temp, String fileName, String mimeType, boolean video) {
|
||||
this.temp = temp;
|
||||
this.fileName = fileName;
|
||||
this.mimeType = mimeType;
|
||||
this.video = video;
|
||||
}
|
||||
}
|
||||
|
||||
/// 开始一次写入,返回后续分块要用的 id
|
||||
@PluginMethod
|
||||
public void begin(PluginCall call) {
|
||||
String fileName = call.getString("fileName");
|
||||
String mimeType = call.getString("mimeType");
|
||||
String mediaType = call.getString("mediaType", "image");
|
||||
if (fileName == null || !fileName.matches("[\\w.\\-]{1,120}")) {
|
||||
call.reject("文件名不合法");
|
||||
return;
|
||||
}
|
||||
if (mimeType == null || !mimeType.matches("(image|video)/[\\w.+-]+")) {
|
||||
call.reject("媒体类型不合法");
|
||||
return;
|
||||
}
|
||||
File directory = new File(getContext().getCacheDir(), "media-save");
|
||||
if (!directory.exists() && !directory.mkdirs()) {
|
||||
call.reject("无法创建缓存目录");
|
||||
return;
|
||||
}
|
||||
String id = UUID.randomUUID().toString();
|
||||
Session session = new Session(new File(directory, id + ".part"), fileName, mimeType, "video".equals(mediaType));
|
||||
sessions.put(id, session);
|
||||
JSObject result = new JSObject();
|
||||
result.put("id", id);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
/// 追加一块 base64 数据
|
||||
@PluginMethod
|
||||
public void append(PluginCall call) {
|
||||
String id = call.getString("id");
|
||||
String data = call.getString("data");
|
||||
Session session = id == null ? null : sessions.get(id);
|
||||
if (session == null) {
|
||||
call.reject("会话不存在");
|
||||
return;
|
||||
}
|
||||
if (data == null) {
|
||||
call.reject("数据为空");
|
||||
return;
|
||||
}
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
byte[] bytes = Base64.decode(data, Base64.DEFAULT);
|
||||
if (MAX_BYTES < session.size + bytes.length) {
|
||||
throw new IllegalStateException("文件超过大小上限");
|
||||
}
|
||||
try (FileOutputStream output = new FileOutputStream(session.temp, true)) {
|
||||
output.write(bytes);
|
||||
}
|
||||
session.size += bytes.length;
|
||||
call.resolve();
|
||||
} catch (Exception e) {
|
||||
sessions.remove(id);
|
||||
session.temp.delete();
|
||||
call.reject("写入失败", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 收尾:把临时文件搬进相册,成功后清理临时文件
|
||||
@PluginMethod
|
||||
public void finish(PluginCall call) {
|
||||
String id = call.getString("id");
|
||||
Session session = id == null ? null : sessions.remove(id);
|
||||
if (session == null) {
|
||||
call.reject("会话不存在");
|
||||
return;
|
||||
}
|
||||
executor.execute(() -> {
|
||||
Uri uri = null;
|
||||
try {
|
||||
ContentResolver resolver = getContext().getContentResolver();
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(MediaStore.MediaColumns.DISPLAY_NAME, session.fileName);
|
||||
values.put(MediaStore.MediaColumns.MIME_TYPE, session.mimeType);
|
||||
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/GaoCustomer");
|
||||
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
|
||||
Uri collection = session.video
|
||||
? MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
|
||||
: MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
|
||||
uri = resolver.insert(collection, values);
|
||||
if (uri == null) {
|
||||
throw new IllegalStateException("无法创建相册条目");
|
||||
}
|
||||
try (InputStream input = new FileInputStream(session.temp); OutputStream output = resolver.openOutputStream(uri)) {
|
||||
if (output == null) {
|
||||
throw new IllegalStateException("无法写入相册");
|
||||
}
|
||||
byte[] buffer = new byte[32768];
|
||||
int size;
|
||||
while ((size = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, size);
|
||||
}
|
||||
}
|
||||
// 清掉 PENDING,相册 App 才会看到这个文件
|
||||
ContentValues done = new ContentValues();
|
||||
done.put(MediaStore.MediaColumns.IS_PENDING, 0);
|
||||
resolver.update(uri, done, null, null);
|
||||
session.temp.delete();
|
||||
call.resolve();
|
||||
} catch (Exception e) {
|
||||
if (uri != null) {
|
||||
try {
|
||||
getContext().getContentResolver().delete(uri, null, null);
|
||||
} catch (Exception ignored) {
|
||||
// 清理失败不影响主流程
|
||||
}
|
||||
}
|
||||
session.temp.delete();
|
||||
call.reject("保存到相册失败", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 放弃本次写入
|
||||
@PluginMethod
|
||||
public void cancel(PluginCall call) {
|
||||
String id = call.getString("id");
|
||||
Session session = id == null ? null : sessions.remove(id);
|
||||
if (session != null) {
|
||||
session.temp.delete();
|
||||
}
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleOnDestroy() {
|
||||
executor.shutdown();
|
||||
for (Session session : sessions.values()) {
|
||||
session.temp.delete();
|
||||
}
|
||||
sessions.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.content.pm.PackageManager;
|
||||
|
||||
import androidx.biometric.BiometricManager;
|
||||
import androidx.biometric.BiometricPrompt;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
/**
|
||||
* 指纹 / 面容解锁。
|
||||
*
|
||||
* <p>只做「闸门」:解锁成功后由前端调 {@code readSession()} 取登录态。
|
||||
* 是否要求「每次读会话都必须过生物识别」由前端控制,原生不强制 —— 业务上存在
|
||||
* 「解锁一次、当天免密」的需求。
|
||||
*/
|
||||
final class BiometricHelper {
|
||||
|
||||
private BiometricHelper() {
|
||||
}
|
||||
|
||||
static void available(FragmentActivity activity, PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
int status;
|
||||
try {
|
||||
status = BiometricManager.from(activity)
|
||||
.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK);
|
||||
} catch (Exception error) {
|
||||
result.put("available", false);
|
||||
result.put("type", "none");
|
||||
call.resolve(result);
|
||||
return;
|
||||
}
|
||||
|
||||
result.put("available", status == BiometricManager.BIOMETRIC_SUCCESS);
|
||||
result.put("type", detectType(activity));
|
||||
if (status != BiometricManager.BIOMETRIC_SUCCESS) {
|
||||
result.put("reason", statusName(status));
|
||||
}
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
static void unlock(FragmentActivity activity, PluginCall call) {
|
||||
int status = BiometricManager.from(activity)
|
||||
.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK);
|
||||
if (status != BiometricManager.BIOMETRIC_SUCCESS) {
|
||||
call.reject("设备不支持生物识别:" + statusName(status), "unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
String title = call.getString("title", "验证身份");
|
||||
String subtitle = call.getString("subtitle", "使用指纹或面容继续");
|
||||
String cancelText = call.getString("cancelText", "改用密码");
|
||||
|
||||
BiometricPrompt.PromptInfo info = new BiometricPrompt.PromptInfo.Builder()
|
||||
.setTitle(title)
|
||||
.setSubtitle(subtitle)
|
||||
.setNegativeButtonText(cancelText)
|
||||
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_WEAK)
|
||||
.setConfirmationRequired(false)
|
||||
.build();
|
||||
|
||||
BiometricPrompt prompt = new BiometricPrompt(
|
||||
activity,
|
||||
ContextCompat.getMainExecutor(activity),
|
||||
new BiometricPrompt.AuthenticationCallback() {
|
||||
@Override
|
||||
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
|
||||
JSObject payload = new JSObject();
|
||||
payload.put("ok", true);
|
||||
call.resolve(payload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAuthenticationError(int errorCode, CharSequence errString) {
|
||||
call.reject(errString == null ? "验证失败" : errString.toString(), "auth_error:" + errorCode);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
try {
|
||||
prompt.authenticate(info);
|
||||
} catch (Exception error) {
|
||||
call.reject("无法启动生物识别", "prompt_failed");
|
||||
}
|
||||
}
|
||||
|
||||
private static String detectType(FragmentActivity activity) {
|
||||
PackageManager manager = activity.getPackageManager();
|
||||
if (manager.hasSystemFeature(PackageManager.FEATURE_FACE)) {
|
||||
return "face";
|
||||
}
|
||||
if (manager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
|
||||
return "fingerprint";
|
||||
}
|
||||
if (manager.hasSystemFeature(PackageManager.FEATURE_IRIS)) {
|
||||
return "iris";
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
|
||||
/** 用字面量而不是常量引用,避免不同 androidx.biometric 版本之间的常量差异 */
|
||||
private static String statusName(int status) {
|
||||
switch (status) {
|
||||
case 12:
|
||||
return "no_hardware";
|
||||
case 1:
|
||||
return "hw_unavailable";
|
||||
case 11:
|
||||
return "none_enrolled";
|
||||
case 15:
|
||||
return "security_update_required";
|
||||
case -2:
|
||||
return "unsupported";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
/**
|
||||
* 重启与覆盖安装后的恢复。
|
||||
*
|
||||
* <p>Android 在重启时会清空所有 AlarmManager 闹钟,不做恢复的话,用户在重启手机之后
|
||||
* 就再也收不到任何本地提醒 —— 这是这类功能最常见的静默失效原因。
|
||||
*/
|
||||
public class BootReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
NotificationScheduler.ensureChannels(context);
|
||||
NotificationScheduler.restore(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothSocket;
|
||||
import android.content.Context;
|
||||
import android.util.Base64;
|
||||
|
||||
import com.getcapacitor.JSArray;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* 蓝牙 ESC/POS 打印。
|
||||
*
|
||||
* <p>原生只负责「连上、写字节、断开」,小票模板、字段顺序、中文位图渲染全部由前端完成。
|
||||
* 这样以后改排版不需要开壳。
|
||||
*
|
||||
* <p>走 SPP(串口协议),UUID 是蓝牙打印机的通用服务号,不需要第三方 SDK。
|
||||
*/
|
||||
final class BtPrinterHelper {
|
||||
|
||||
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
|
||||
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
|
||||
|
||||
private BtPrinterHelper() {
|
||||
}
|
||||
|
||||
/** 列出已配对设备;未配对的打印机需要用户先在系统设置里配对 */
|
||||
static void list(Context context, PluginCall call) {
|
||||
BluetoothAdapter adapter = adapterOf(context);
|
||||
if (adapter == null) {
|
||||
call.reject("蓝牙不可用", "service_unavailable");
|
||||
return;
|
||||
}
|
||||
if (!adapter.isEnabled()) {
|
||||
call.reject("蓝牙未开启", "disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
JSArray printers = new JSArray();
|
||||
try {
|
||||
Set<BluetoothDevice> bonded = adapter.getBondedDevices();
|
||||
for (BluetoothDevice device : bonded) {
|
||||
JSObject item = new JSObject();
|
||||
item.put("name", device.getName() == null ? "" : device.getName());
|
||||
item.put("address", device.getAddress());
|
||||
item.put("bonded", true);
|
||||
printers.put(item);
|
||||
}
|
||||
} catch (SecurityException error) {
|
||||
call.reject("未授予蓝牙权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("printers", printers);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
static void printRaw(Context context, PluginCall call) {
|
||||
String address = call.getString("address");
|
||||
String data = call.getString("data");
|
||||
if (address == null || !address.matches("([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}")) {
|
||||
call.reject("打印机地址不合法", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
if (data == null || data.isEmpty()) {
|
||||
call.reject("缺少打印数据", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] bytes;
|
||||
try {
|
||||
bytes = Base64.decode(data, Base64.DEFAULT);
|
||||
} catch (Exception error) {
|
||||
call.reject("打印数据不是合法的 base64", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
BluetoothAdapter adapter = adapterOf(context);
|
||||
if (adapter == null) {
|
||||
call.reject("蓝牙不可用", "service_unavailable");
|
||||
return;
|
||||
}
|
||||
if (!adapter.isEnabled()) {
|
||||
call.reject("蓝牙未开启", "disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
EXECUTOR.execute(() -> {
|
||||
BluetoothSocket socket = null;
|
||||
try {
|
||||
BluetoothDevice device = adapter.getRemoteDevice(address);
|
||||
adapter.cancelDiscovery();
|
||||
socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
|
||||
socket.connect();
|
||||
|
||||
OutputStream output = socket.getOutputStream();
|
||||
output.write(bytes);
|
||||
output.flush();
|
||||
// 给打印机留出出纸时间,立刻 close 会截断最后一行
|
||||
Thread.sleep(200);
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("bytes", bytes.length);
|
||||
call.resolve(result);
|
||||
} catch (SecurityException error) {
|
||||
call.reject("未授予蓝牙权限", "permission_denied");
|
||||
} catch (Exception error) {
|
||||
call.reject("打印失败:" + error.getMessage(), "bt_failed");
|
||||
} finally {
|
||||
if (socket != null) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (Exception ignored) {
|
||||
// 关闭失败不影响结果
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static BluetoothAdapter adapterOf(Context context) {
|
||||
BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
return manager == null ? null : manager.getAdapter();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.Activity;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.ContentUris;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.provider.CalendarContract;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.getcapacitor.JSArray;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
|
||||
/**
|
||||
* 写入系统日历。
|
||||
*
|
||||
* <p>这是 Android 唯一跨厂商的「日程 / 提醒事项」入口:各家的备忘录、待办应用都是私有数据库,
|
||||
* 没有标准 ContentProvider,也没有统一的 Intent 契约,做不了。日历走 {@link CalendarContract},
|
||||
* 小米 / 华为 / OPPO 的日历都是 AOSP Calendar 改的,基本都响应。
|
||||
*
|
||||
* <p>两条写入路径:
|
||||
* <ul>
|
||||
* <li>静默写入:需要 READ_CALENDAR / WRITE_CALENDAR,且设备上存在可写日历,成功后返回 eventId</li>
|
||||
* <li>拉起界面:不需要任何权限,弹系统日历新建页由用户确认,拿不到 eventId</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>国产 ROM 常见的坑是「没有任何本地日历账户」,此时 Calendars 表为空,静默写入无日历可选,
|
||||
* 只能降级到拉起界面。所以 auto 模式默认先试静默、失败再开界面。
|
||||
*/
|
||||
final class CalendarHelper {
|
||||
|
||||
private static final String EVENT_MIME_TYPE = "vnd.android.cursor.dir/event";
|
||||
private static final long DEFAULT_DURATION = 30 * 60 * 1000L;
|
||||
private static final int DEFAULT_REMINDER_MINUTES = 0;
|
||||
|
||||
private CalendarHelper() {
|
||||
}
|
||||
|
||||
// ---------- 探测 ----------
|
||||
|
||||
static void available(Context context, PluginCall call) {
|
||||
boolean hasPermission = hasWritePermission(context);
|
||||
List<CalendarEntry> calendars = hasPermission ? queryWritable(context) : new ArrayList<>();
|
||||
|
||||
JSArray items = new JSArray();
|
||||
for (CalendarEntry entry : calendars) {
|
||||
JSObject item = new JSObject();
|
||||
item.put("id", String.valueOf(entry.id));
|
||||
item.put("name", entry.name);
|
||||
item.put("accountName", entry.accountName);
|
||||
item.put("accountType", entry.accountType);
|
||||
item.put("primary", entry.primary);
|
||||
items.put(item);
|
||||
}
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("canInsert", hasCalendarApp(context));
|
||||
result.put("canWriteSilent", hasPermission && !calendars.isEmpty());
|
||||
result.put("calendars", items);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---------- 写入 ----------
|
||||
|
||||
static void add(Activity activity, PluginCall call) {
|
||||
Payload payload = Payload.from(call);
|
||||
if (payload == null) {
|
||||
call.reject("缺少标题或开始时间", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
String mode = call.getString("mode", "auto");
|
||||
boolean writable = hasWritePermission(activity);
|
||||
long calendarId = writable ? resolveCalendarId(activity, call.getString("calendarId")) : -1;
|
||||
|
||||
if ("silent".equals(mode)) {
|
||||
if (!writable) {
|
||||
call.reject("未授予日历写入权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
if (calendarId <= 0) {
|
||||
call.reject("设备上没有可写的日历账户", "no_writable_calendar");
|
||||
return;
|
||||
}
|
||||
insert(activity, call, payload, calendarId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!"intent".equals(mode) && 0 < calendarId) {
|
||||
insert(activity, call, payload, calendarId);
|
||||
return;
|
||||
}
|
||||
|
||||
openIntent(activity, call, payload);
|
||||
}
|
||||
|
||||
private static void insert(Activity activity, PluginCall call, Payload payload, long calendarId) {
|
||||
ContentResolver resolver = activity.getContentResolver();
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
|
||||
values.put(CalendarContract.Events.TITLE, payload.title);
|
||||
values.put(CalendarContract.Events.DTSTART, payload.beginAt);
|
||||
values.put(CalendarContract.Events.DTEND, payload.endAt);
|
||||
values.put(CalendarContract.Events.HAS_ALARM, 1);
|
||||
values.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
|
||||
|
||||
if (payload.description != null) {
|
||||
values.put(CalendarContract.Events.DESCRIPTION, payload.description);
|
||||
}
|
||||
if (payload.location != null) {
|
||||
values.put(CalendarContract.Events.EVENT_LOCATION, payload.location);
|
||||
}
|
||||
|
||||
if (payload.allDay) {
|
||||
// 全天事件的起止必须是 UTC 午夜,时区固定 UTC,否则会整体偏移一天
|
||||
values.put(CalendarContract.Events.ALL_DAY, 1);
|
||||
values.put(CalendarContract.Events.EVENT_TIMEZONE, "UTC");
|
||||
} else {
|
||||
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
|
||||
}
|
||||
|
||||
Uri uri;
|
||||
try {
|
||||
uri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
|
||||
} catch (Exception error) {
|
||||
call.reject("写入日历失败:" + error.getMessage(), "insert_failed");
|
||||
return;
|
||||
}
|
||||
if (uri == null) {
|
||||
call.reject("写入日历失败", "insert_failed");
|
||||
return;
|
||||
}
|
||||
|
||||
long eventId = ContentUris.parseId(uri);
|
||||
for (int minutes : payload.reminderMinutes) {
|
||||
try {
|
||||
ContentValues reminder = new ContentValues();
|
||||
reminder.put(CalendarContract.Reminders.EVENT_ID, eventId);
|
||||
reminder.put(CalendarContract.Reminders.MINUTES, minutes);
|
||||
reminder.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
|
||||
resolver.insert(CalendarContract.Reminders.CONTENT_URI, reminder);
|
||||
} catch (Exception ignored) {
|
||||
// 提醒建不上不影响事件本身,日历 App 会用自己的默认提醒策略
|
||||
}
|
||||
}
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("mode", "silent");
|
||||
result.put("eventId", String.valueOf(eventId));
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
private static void openIntent(Activity activity, PluginCall call, Payload payload) {
|
||||
Intent intent = new Intent(Intent.ACTION_INSERT);
|
||||
intent.setDataAndType(CalendarContract.Events.CONTENT_URI, EVENT_MIME_TYPE);
|
||||
intent.putExtra(CalendarContract.Events.TITLE, payload.title);
|
||||
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, payload.beginAt);
|
||||
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, payload.endAt);
|
||||
intent.putExtra(CalendarContract.Events.ALL_DAY, payload.allDay);
|
||||
intent.putExtra(CalendarContract.Events.HAS_ALARM, 1);
|
||||
intent.putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
|
||||
|
||||
if (payload.description != null) {
|
||||
intent.putExtra(CalendarContract.Events.DESCRIPTION, payload.description);
|
||||
}
|
||||
if (payload.location != null) {
|
||||
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, payload.location);
|
||||
}
|
||||
// 这个 extra 不是所有日历 App 都认,认不了就用应用自己的默认提醒
|
||||
if (!payload.reminderMinutes.isEmpty()) {
|
||||
intent.putExtra(CalendarContract.Reminders.MINUTES, payload.reminderMinutes.get(0));
|
||||
}
|
||||
|
||||
try {
|
||||
activity.startActivity(intent);
|
||||
JSObject result = new JSObject();
|
||||
result.put("mode", "intent");
|
||||
result.put("eventId", JSObject.NULL);
|
||||
call.resolve(result);
|
||||
} catch (ActivityNotFoundException error) {
|
||||
call.reject("设备上没有可用的日历应用", "no_calendar_app");
|
||||
} catch (Exception error) {
|
||||
call.reject("无法打开日历:" + error.getMessage(), "activity_not_found");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 删除 ----------
|
||||
|
||||
static void remove(Context context, PluginCall call) {
|
||||
String eventId = call.getString("eventId");
|
||||
if (eventId == null || eventId.isEmpty()) {
|
||||
call.reject("缺少 eventId", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
long id;
|
||||
try {
|
||||
id = Long.parseLong(eventId);
|
||||
} catch (NumberFormatException error) {
|
||||
call.reject("eventId 不合法", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
|
||||
int deleted = context.getContentResolver().delete(uri, null, null);
|
||||
JSObject result = new JSObject();
|
||||
result.put("deleted", 0 < deleted);
|
||||
call.resolve(result);
|
||||
} catch (Exception error) {
|
||||
call.reject("删除日程失败:" + error.getMessage(), "delete_failed");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 内部 ----------
|
||||
|
||||
private static boolean hasWritePermission(Context context) {
|
||||
return ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR)
|
||||
== PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
private static boolean hasCalendarApp(Context context) {
|
||||
try {
|
||||
Intent intent = new Intent(Intent.ACTION_INSERT);
|
||||
intent.setDataAndType(CalendarContract.Events.CONTENT_URI, EVENT_MIME_TYPE);
|
||||
List<ResolveInfo> list = context.getPackageManager()
|
||||
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
|
||||
return list != null && !list.isEmpty();
|
||||
} catch (Exception error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<CalendarEntry> queryWritable(Context context) {
|
||||
List<CalendarEntry> result = new ArrayList<>();
|
||||
String[] projection = {
|
||||
CalendarContract.Calendars._ID,
|
||||
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
|
||||
CalendarContract.Calendars.ACCOUNT_NAME,
|
||||
CalendarContract.Calendars.ACCOUNT_TYPE,
|
||||
CalendarContract.Calendars.IS_PRIMARY
|
||||
};
|
||||
String selection = CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL + ">=?";
|
||||
String[] args = { String.valueOf(CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR) };
|
||||
|
||||
try (Cursor cursor = context.getContentResolver().query(
|
||||
CalendarContract.Calendars.CONTENT_URI,
|
||||
projection,
|
||||
selection,
|
||||
args,
|
||||
null
|
||||
)) {
|
||||
if (cursor == null) {
|
||||
return result;
|
||||
}
|
||||
while (cursor.moveToNext()) {
|
||||
CalendarEntry entry = new CalendarEntry();
|
||||
entry.id = cursor.getLong(0);
|
||||
entry.name = cursor.getString(1) == null ? "" : cursor.getString(1);
|
||||
entry.accountName = cursor.getString(2) == null ? "" : cursor.getString(2);
|
||||
entry.accountType = cursor.getString(3) == null ? "" : cursor.getString(3);
|
||||
entry.primary = 0 < cursor.getInt(4);
|
||||
result.add(entry);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 部分 ROM 的 provider 会抛异常,按「没有可写日历」处理,由上层降级到 Intent
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 选日历:指定 id > 主日历 > 本地日历 > 第一个 */
|
||||
private static long resolveCalendarId(Context context, String preferred) {
|
||||
List<CalendarEntry> list = queryWritable(context);
|
||||
if (list.isEmpty()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (preferred != null && !preferred.isEmpty()) {
|
||||
for (CalendarEntry entry : list) {
|
||||
if (preferred.equals(String.valueOf(entry.id))) {
|
||||
return entry.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (CalendarEntry entry : list) {
|
||||
if (entry.primary) {
|
||||
return entry.id;
|
||||
}
|
||||
}
|
||||
for (CalendarEntry entry : list) {
|
||||
if ("LOCAL".equals(entry.accountType)) {
|
||||
return entry.id;
|
||||
}
|
||||
}
|
||||
return list.get(0).id;
|
||||
}
|
||||
|
||||
private static final class CalendarEntry {
|
||||
long id;
|
||||
String name;
|
||||
String accountName;
|
||||
String accountType;
|
||||
boolean primary;
|
||||
}
|
||||
|
||||
/** 入参解析一次,避免在多个分支里重复取值 */
|
||||
private static final class Payload {
|
||||
String title;
|
||||
String description;
|
||||
String location;
|
||||
long beginAt;
|
||||
long endAt;
|
||||
boolean allDay;
|
||||
List<Integer> reminderMinutes = new ArrayList<>();
|
||||
|
||||
static Payload from(PluginCall call) {
|
||||
String title = call.getString("title");
|
||||
Long beginAt = call.getLong("beginAt");
|
||||
if (title == null || title.isEmpty() || beginAt == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Payload payload = new Payload();
|
||||
payload.title = title;
|
||||
payload.description = call.getString("description");
|
||||
payload.location = call.getString("location");
|
||||
payload.beginAt = beginAt;
|
||||
payload.allDay = Boolean.TRUE.equals(call.getBoolean("allDay", false));
|
||||
|
||||
Long endAt = call.getLong("endAt");
|
||||
payload.endAt = endAt == null || endAt <= beginAt ? beginAt + DEFAULT_DURATION : endAt;
|
||||
if (payload.allDay && payload.endAt <= payload.beginAt) {
|
||||
payload.endAt = payload.beginAt + 24 * 60 * 60 * 1000L;
|
||||
}
|
||||
|
||||
JSArray minutes = call.getArray("reminderMinutes");
|
||||
if (minutes != null) {
|
||||
for (int index = 0; index < minutes.length(); index++) {
|
||||
Object item = minutes.opt(index);
|
||||
if (item instanceof Number) {
|
||||
payload.reminderMinutes.add(((Number) item).intValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (payload.reminderMinutes.isEmpty()) {
|
||||
payload.reminderMinutes.add(DEFAULT_REMINDER_MINUTES);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,805 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RectF;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.VibrationEffect;
|
||||
import android.os.Vibrator;
|
||||
import android.util.Size;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.activity.OnBackPressedCallback;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.camera.core.Camera;
|
||||
import androidx.camera.core.CameraSelector;
|
||||
import androidx.camera.core.ImageAnalysis;
|
||||
import androidx.camera.core.ImageCapture;
|
||||
import androidx.camera.core.ImageCaptureException;
|
||||
import androidx.camera.core.ImageProxy;
|
||||
import androidx.camera.core.Preview;
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider;
|
||||
import androidx.camera.view.PreviewView;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.core.view.ViewCompat;
|
||||
import androidx.core.view.WindowCompat;
|
||||
import androidx.core.view.WindowInsetsCompat;
|
||||
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.BinaryBitmap;
|
||||
import com.google.zxing.DecodeHintType;
|
||||
import com.google.zxing.MultiFormatReader;
|
||||
import com.google.zxing.NotFoundException;
|
||||
import com.google.zxing.PlanarYUVLuminanceSource;
|
||||
import com.google.zxing.Result;
|
||||
import com.google.zxing.RGBLuminanceSource;
|
||||
import com.google.zxing.common.HybridBinarizer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* 扫码与拍照共用的相机页。
|
||||
*
|
||||
* <p>两条模式共用同一条 CameraX 管线:扫码绑 Preview + ImageAnalysis,拍照绑 Preview + ImageCapture。
|
||||
* UI 只做取景、手电筒、相册、快门,不放任何业务文案 —— 文案一进原生,改一个字都要发壳。
|
||||
*
|
||||
* <p>解码用 zxing 的纯 JVM 实现,不依赖 Google Play 服务,国产 ROM 上同样可用。
|
||||
*/
|
||||
public class CameraKitActivity extends AppCompatActivity {
|
||||
|
||||
public static final String EXTRA_MODE = "mode";
|
||||
public static final String MODE_SCAN = "scan";
|
||||
public static final String MODE_CAPTURE = "capture";
|
||||
|
||||
public static final String EXTRA_FORMATS = "formats";
|
||||
public static final String EXTRA_TORCH = "torch";
|
||||
public static final String EXTRA_CONTINUOUS = "continuous";
|
||||
public static final String EXTRA_MULTIPLE = "multiple";
|
||||
public static final String EXTRA_MAX_COUNT = "maxCount";
|
||||
public static final String EXTRA_FACING = "facing";
|
||||
public static final String EXTRA_FLASH = "flash";
|
||||
|
||||
public static final String FACING_BACK = "back";
|
||||
public static final String FACING_FRONT = "front";
|
||||
|
||||
public static final String RESULT_TEXT = "text";
|
||||
public static final String RESULT_FORMAT = "format";
|
||||
public static final String RESULT_FILES = "files";
|
||||
|
||||
private static final int REQUEST_GALLERY = 0x9001;
|
||||
private static final String[] DEFAULT_FORMATS = {
|
||||
"QR_CODE", "CODE_128", "CODE_39", "EAN_13", "EAN_8"
|
||||
};
|
||||
|
||||
private final ExecutorService decodeExecutor = Executors.newSingleThreadExecutor();
|
||||
private final AtomicBoolean decoding = new AtomicBoolean(false);
|
||||
private final List<String> capturedPaths = new ArrayList<>();
|
||||
private final MultiFormatReader reader = new MultiFormatReader();
|
||||
private Map<DecodeHintType, Object> hints;
|
||||
|
||||
private PreviewView previewView;
|
||||
private TextView torchButton;
|
||||
private TextView counterView;
|
||||
private TextView hintView;
|
||||
private View shutterButton;
|
||||
private View galleryButton;
|
||||
|
||||
private ProcessCameraProvider cameraProvider;
|
||||
private Camera camera;
|
||||
private ImageCapture imageCapture;
|
||||
|
||||
private String mode = MODE_SCAN;
|
||||
private boolean continuous;
|
||||
private boolean multiple;
|
||||
private int maxCount = 9;
|
||||
private boolean facingFront;
|
||||
private boolean flashOn;
|
||||
private boolean torchOn;
|
||||
private boolean capturing;
|
||||
private String lastText;
|
||||
private String lastFormat;
|
||||
private File outputDir;
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
mode = getIntent().getStringExtra(EXTRA_MODE);
|
||||
if (MODE_CAPTURE.equals(mode)) {
|
||||
mode = MODE_CAPTURE;
|
||||
} else {
|
||||
mode = MODE_SCAN;
|
||||
}
|
||||
|
||||
continuous = getIntent().getBooleanExtra(EXTRA_CONTINUOUS, false);
|
||||
multiple = getIntent().getBooleanExtra(EXTRA_MULTIPLE, false);
|
||||
maxCount = Math.max(1, getIntent().getIntExtra(EXTRA_MAX_COUNT, 9));
|
||||
facingFront = FACING_FRONT.equals(getIntent().getStringExtra(EXTRA_FACING));
|
||||
flashOn = getIntent().getBooleanExtra(EXTRA_FLASH, false);
|
||||
torchOn = getIntent().getBooleanExtra(EXTRA_TORCH, false);
|
||||
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
|
||||
!= PackageManager.PERMISSION_GRANTED) {
|
||||
setResult(RESULT_CANCELED);
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
outputDir = new File(getCacheDir(), "camera-kit");
|
||||
if (!outputDir.exists()) {
|
||||
outputDir.mkdirs();
|
||||
}
|
||||
|
||||
hints = buildHints();
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
|
||||
buildUi();
|
||||
startCamera();
|
||||
registerBackHandler();
|
||||
}
|
||||
|
||||
// ---------- UI ----------
|
||||
|
||||
private void buildUi() {
|
||||
FrameLayout root = new FrameLayout(this);
|
||||
root.setBackgroundColor(Color.BLACK);
|
||||
|
||||
previewView = new PreviewView(this);
|
||||
previewView.setScaleType(PreviewView.ScaleType.FILL_CENTER);
|
||||
root.addView(previewView, new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
));
|
||||
|
||||
if (MODE_SCAN.equals(mode)) {
|
||||
root.addView(new FrameOverlay(this), new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
));
|
||||
}
|
||||
|
||||
// 顶部栏:返回、标题、手电筒
|
||||
LinearLayout topBar = new LinearLayout(this);
|
||||
topBar.setOrientation(LinearLayout.HORIZONTAL);
|
||||
topBar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
topBar.setPadding(dp(8), dp(8), dp(8), dp(8));
|
||||
|
||||
TextView closeButton = actionText("✕");
|
||||
closeButton.setOnClickListener(view -> handleClose());
|
||||
topBar.addView(closeButton, new LinearLayout.LayoutParams(dp(48), dp(48)));
|
||||
|
||||
TextView titleView = new TextView(this);
|
||||
titleView.setText(MODE_SCAN.equals(mode) ? "扫码" : "拍照");
|
||||
titleView.setTextColor(Color.WHITE);
|
||||
titleView.setTextSize(16f);
|
||||
LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(
|
||||
0,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
1f
|
||||
);
|
||||
topBar.addView(titleView, titleParams);
|
||||
|
||||
torchButton = actionText("手电筒");
|
||||
torchButton.setOnClickListener(view -> toggleTorch());
|
||||
topBar.addView(torchButton, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
dp(48)
|
||||
));
|
||||
updateTorchLabel();
|
||||
|
||||
FrameLayout.LayoutParams topParams = new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
Gravity.TOP
|
||||
);
|
||||
root.addView(topBar, topParams);
|
||||
ViewCompat.setOnApplyWindowInsetsListener(root, (view, insets) -> {
|
||||
androidx.core.graphics.Insets bars = insets.getInsets(
|
||||
WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout()
|
||||
);
|
||||
topBar.setPadding(dp(8), dp(8) + bars.top, dp(8), dp(8));
|
||||
return insets;
|
||||
});
|
||||
|
||||
// 底部栏
|
||||
LinearLayout bottomBar = new LinearLayout(this);
|
||||
bottomBar.setOrientation(LinearLayout.VERTICAL);
|
||||
bottomBar.setGravity(Gravity.CENTER_HORIZONTAL);
|
||||
bottomBar.setPadding(dp(16), dp(16), dp(16), dp(24));
|
||||
|
||||
hintView = new TextView(this);
|
||||
hintView.setTextColor(Color.WHITE);
|
||||
hintView.setTextSize(13f);
|
||||
hintView.setGravity(Gravity.CENTER);
|
||||
hintView.setText(MODE_SCAN.equals(mode) ? "将二维码移入取景框" : "点击拍摄");
|
||||
bottomBar.addView(hintView, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
));
|
||||
|
||||
counterView = new TextView(this);
|
||||
counterView.setTextColor(Color.WHITE);
|
||||
counterView.setTextSize(13f);
|
||||
counterView.setGravity(Gravity.CENTER);
|
||||
counterView.setVisibility(multiple ? View.VISIBLE : View.GONE);
|
||||
bottomBar.addView(counterView, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
));
|
||||
|
||||
FrameLayout actionRow = new FrameLayout(this);
|
||||
actionRow.setLayoutParams(new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
dp(96)
|
||||
));
|
||||
|
||||
if (MODE_SCAN.equals(mode)) {
|
||||
galleryButton = pillText("相册");
|
||||
galleryButton.setOnClickListener(view -> pickFromGallery());
|
||||
FrameLayout.LayoutParams galleryParams = new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
dp(40),
|
||||
Gravity.CENTER_VERTICAL | Gravity.START
|
||||
);
|
||||
actionRow.addView(galleryButton, galleryParams);
|
||||
} else {
|
||||
shutterButton = new View(this);
|
||||
android.graphics.drawable.GradientDrawable circle = new android.graphics.drawable.GradientDrawable();
|
||||
circle.setShape(android.graphics.drawable.GradientDrawable.OVAL);
|
||||
circle.setColor(Color.WHITE);
|
||||
circle.setStroke(dp(4), 0x66FFFFFF);
|
||||
shutterButton.setBackground(circle);
|
||||
shutterButton.setOnClickListener(view -> takePicture());
|
||||
FrameLayout.LayoutParams shutterParams = new FrameLayout.LayoutParams(dp(72), dp(72), Gravity.CENTER);
|
||||
actionRow.addView(shutterButton, shutterParams);
|
||||
|
||||
if (multiple) {
|
||||
TextView doneButton = pillText("完成");
|
||||
doneButton.setOnClickListener(view -> {
|
||||
if (capturedPaths.isEmpty()) {
|
||||
setResult(RESULT_CANCELED);
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
finishWithFiles();
|
||||
});
|
||||
actionRow.addView(doneButton, new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
dp(40),
|
||||
Gravity.CENTER_VERTICAL | Gravity.END
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
bottomBar.addView(actionRow, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
dp(96)
|
||||
));
|
||||
|
||||
FrameLayout.LayoutParams bottomParams = new FrameLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
Gravity.BOTTOM
|
||||
);
|
||||
root.addView(bottomBar, bottomParams);
|
||||
|
||||
setContentView(root);
|
||||
updateCounter();
|
||||
}
|
||||
|
||||
private TextView actionText(String text) {
|
||||
TextView view = new TextView(this);
|
||||
view.setText(text);
|
||||
view.setTextColor(Color.WHITE);
|
||||
view.setTextSize(14f);
|
||||
view.setGravity(Gravity.CENTER);
|
||||
view.setBackgroundColor(0x33000000);
|
||||
return view;
|
||||
}
|
||||
|
||||
private TextView pillText(String text) {
|
||||
TextView view = new TextView(this);
|
||||
view.setText(text);
|
||||
view.setTextColor(Color.WHITE);
|
||||
view.setTextSize(14f);
|
||||
view.setGravity(Gravity.CENTER);
|
||||
view.setPadding(dp(16), 0, dp(16), 0);
|
||||
android.graphics.drawable.GradientDrawable background = new android.graphics.drawable.GradientDrawable();
|
||||
background.setShape(android.graphics.drawable.GradientDrawable.RECTANGLE);
|
||||
background.setCornerRadius(dp(20));
|
||||
background.setColor(0x66000000);
|
||||
view.setBackground(background);
|
||||
return view;
|
||||
}
|
||||
|
||||
// ---------- 相机 ----------
|
||||
|
||||
private void startCamera() {
|
||||
ListenableFuture<ProcessCameraProvider> future = ProcessCameraProvider.getInstance(this);
|
||||
future.addListener(() -> {
|
||||
try {
|
||||
cameraProvider = future.get();
|
||||
bindUseCases();
|
||||
} catch (Exception error) {
|
||||
finishWithMessage("相机初始化失败");
|
||||
}
|
||||
}, ContextCompat.getMainExecutor(this));
|
||||
}
|
||||
|
||||
private void bindUseCases() {
|
||||
if (cameraProvider == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
CameraSelector selector = facingFront
|
||||
? CameraSelector.DEFAULT_FRONT_CAMERA
|
||||
: CameraSelector.DEFAULT_BACK_CAMERA;
|
||||
try {
|
||||
if (!cameraProvider.hasCamera(selector)) {
|
||||
selector = CameraSelector.DEFAULT_BACK_CAMERA;
|
||||
facingFront = false;
|
||||
}
|
||||
} catch (Exception error) {
|
||||
// 查询相机信息失败时退回后置,不能直接崩
|
||||
selector = CameraSelector.DEFAULT_BACK_CAMERA;
|
||||
facingFront = false;
|
||||
}
|
||||
|
||||
Preview preview = new Preview.Builder().build();
|
||||
preview.setSurfaceProvider(previewView.getSurfaceProvider());
|
||||
|
||||
cameraProvider.unbindAll();
|
||||
if (MODE_SCAN.equals(mode)) {
|
||||
ImageAnalysis analysis = new ImageAnalysis.Builder()
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)
|
||||
.setTargetResolution(new Size(1280, 720))
|
||||
.build();
|
||||
analysis.setAnalyzer(decodeExecutor, this::analyze);
|
||||
camera = cameraProvider.bindToLifecycle(this, selector, preview, analysis);
|
||||
} else {
|
||||
imageCapture = new ImageCapture.Builder()
|
||||
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
|
||||
.setFlashMode(flashOn ? ImageCapture.FLASH_MODE_ON : ImageCapture.FLASH_MODE_OFF)
|
||||
.build();
|
||||
camera = cameraProvider.bindToLifecycle(this, selector, preview, imageCapture);
|
||||
}
|
||||
|
||||
if (torchOn) {
|
||||
applyTorch(true);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 扫码 ----------
|
||||
|
||||
private void analyze(ImageProxy imageProxy) {
|
||||
if (!decoding.compareAndSet(false, true)) {
|
||||
imageProxy.close();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
int width = imageProxy.getWidth();
|
||||
int height = imageProxy.getHeight();
|
||||
byte[] data = yuvToLuminance(imageProxy, width, height);
|
||||
if (data == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
int rotation = imageProxy.getImageInfo().getRotationDegrees();
|
||||
if (90 == rotation || 270 == rotation) {
|
||||
data = rotate90(data, width, height, 270 == rotation);
|
||||
int swap = width;
|
||||
width = height;
|
||||
height = swap;
|
||||
} else if (180 == rotation) {
|
||||
data = rotate180(data, width, height);
|
||||
}
|
||||
|
||||
PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(
|
||||
data,
|
||||
width,
|
||||
height,
|
||||
0,
|
||||
0,
|
||||
width,
|
||||
height,
|
||||
false
|
||||
);
|
||||
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
|
||||
Result result = reader.decode(bitmap, hints);
|
||||
if (result != null && result.getText() != null && !result.getText().isEmpty()) {
|
||||
runOnUiThread(() -> onDecoded(result.getText(), result.getBarcodeFormat()));
|
||||
}
|
||||
} catch (NotFoundException ignored) {
|
||||
// 大多数帧都不会命中,这是正常路径
|
||||
} catch (Exception ignored) {
|
||||
// 单帧解码失败不影响后续帧
|
||||
} finally {
|
||||
decoding.set(false);
|
||||
imageProxy.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void onDecoded(String text, BarcodeFormat format) {
|
||||
vibrate();
|
||||
lastText = text;
|
||||
lastFormat = format == null ? "" : format.name();
|
||||
|
||||
if (continuous) {
|
||||
hintView.setText("已识别:" + text);
|
||||
return;
|
||||
}
|
||||
finishWithScan();
|
||||
}
|
||||
|
||||
private void finishWithScan() {
|
||||
Intent data = new Intent();
|
||||
data.putExtra(RESULT_TEXT, lastText == null ? "" : lastText);
|
||||
data.putExtra(RESULT_FORMAT, lastFormat == null ? "" : lastFormat);
|
||||
setResult(RESULT_OK, data);
|
||||
finish();
|
||||
}
|
||||
|
||||
private void pickFromGallery() {
|
||||
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
|
||||
intent.setType("image/*");
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
try {
|
||||
startActivityForResult(intent, REQUEST_GALLERY);
|
||||
} catch (Exception error) {
|
||||
hintView.setText("无法打开相册");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (REQUEST_GALLERY != requestCode || RESULT_OK != resultCode || data == null) {
|
||||
return;
|
||||
}
|
||||
Uri uri = data.getData();
|
||||
if (uri == null) {
|
||||
return;
|
||||
}
|
||||
decodeFromUri(uri);
|
||||
}
|
||||
|
||||
private void decodeFromUri(Uri uri) {
|
||||
decodeExecutor.execute(() -> {
|
||||
Bitmap bitmap = null;
|
||||
try (InputStream input = getContentResolver().openInputStream(uri)) {
|
||||
bitmap = BitmapFactory.decodeStream(input);
|
||||
if (bitmap == null) {
|
||||
showHint("图片读取失败");
|
||||
return;
|
||||
}
|
||||
int width = bitmap.getWidth();
|
||||
int height = bitmap.getHeight();
|
||||
int[] pixels = new int[width * height];
|
||||
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
|
||||
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
|
||||
Result result = reader.decode(new BinaryBitmap(new HybridBinarizer(source)), hints);
|
||||
if (result != null && result.getText() != null && !result.getText().isEmpty()) {
|
||||
runOnUiThread(() -> onDecoded(result.getText(), result.getBarcodeFormat()));
|
||||
return;
|
||||
}
|
||||
showHint("图片里没有识别到条码");
|
||||
} catch (Exception error) {
|
||||
showHint("图片识别失败");
|
||||
} finally {
|
||||
if (bitmap != null) {
|
||||
bitmap.recycle();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 拍照 ----------
|
||||
|
||||
private void takePicture() {
|
||||
if (imageCapture == null || capturing) {
|
||||
return;
|
||||
}
|
||||
capturing = true;
|
||||
|
||||
String name = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.US).format(System.currentTimeMillis()) + ".jpg";
|
||||
File file = new File(outputDir, name);
|
||||
ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(file).build();
|
||||
|
||||
imageCapture.takePicture(options, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
|
||||
@Override
|
||||
public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
|
||||
capturing = false;
|
||||
capturedPaths.add(file.getAbsolutePath());
|
||||
vibrate();
|
||||
updateCounter();
|
||||
|
||||
if (!multiple || maxCount <= capturedPaths.size()) {
|
||||
finishWithFiles();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull ImageCaptureException exception) {
|
||||
capturing = false;
|
||||
hintView.setText("拍照失败:" + exception.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void finishWithFiles() {
|
||||
Intent data = new Intent();
|
||||
data.putStringArrayListExtra(RESULT_FILES, new ArrayList<>(capturedPaths));
|
||||
setResult(RESULT_OK, data);
|
||||
finish();
|
||||
}
|
||||
|
||||
private void updateCounter() {
|
||||
if (counterView == null) {
|
||||
return;
|
||||
}
|
||||
if (!multiple) {
|
||||
counterView.setVisibility(View.GONE);
|
||||
return;
|
||||
}
|
||||
counterView.setVisibility(View.VISIBLE);
|
||||
counterView.setText(String.format(Locale.US, "已拍 %d / %d", capturedPaths.size(), maxCount));
|
||||
}
|
||||
|
||||
// ---------- 手电筒 ----------
|
||||
|
||||
private void toggleTorch() {
|
||||
applyTorch(!torchOn);
|
||||
}
|
||||
|
||||
private void applyTorch(boolean enabled) {
|
||||
if (camera == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
camera.getCameraControl().enableTorch(enabled);
|
||||
torchOn = enabled;
|
||||
updateTorchLabel();
|
||||
} catch (Exception error) {
|
||||
hintView.setText("手电筒不可用");
|
||||
}
|
||||
}
|
||||
|
||||
private void updateTorchLabel() {
|
||||
if (torchButton != null) {
|
||||
torchButton.setText(torchOn ? "关灯" : "手电筒");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 生命周期 ----------
|
||||
|
||||
private void registerBackHandler() {
|
||||
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
|
||||
@Override
|
||||
public void handleOnBackPressed() {
|
||||
handleClose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void handleClose() {
|
||||
if (MODE_SCAN.equals(mode) && continuous && lastText != null) {
|
||||
finishWithScan();
|
||||
return;
|
||||
}
|
||||
setResult(RESULT_CANCELED);
|
||||
finish();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
decoding.set(true);
|
||||
decodeExecutor.shutdownNow();
|
||||
if (cameraProvider != null) {
|
||||
cameraProvider.unbindAll();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 工具 ----------
|
||||
|
||||
private void finishWithMessage(String message) {
|
||||
hintView.setText(message);
|
||||
setResult(RESULT_CANCELED);
|
||||
finish();
|
||||
}
|
||||
|
||||
private void showHint(String message) {
|
||||
runOnUiThread(() -> {
|
||||
if (hintView != null) {
|
||||
hintView.setText(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void vibrate() {
|
||||
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
|
||||
if (vibrator != null && vibrator.hasVibrator()) {
|
||||
vibrator.vibrate(VibrationEffect.createOneShot(40, VibrationEffect.DEFAULT_AMPLITUDE));
|
||||
}
|
||||
}
|
||||
|
||||
private int dp(float value) {
|
||||
return Math.round(value * getResources().getDisplayMetrics().density);
|
||||
}
|
||||
|
||||
private Map<DecodeHintType, Object> buildHints() {
|
||||
List<BarcodeFormat> formats = new ArrayList<>();
|
||||
ArrayList<String> requested = getIntent().getStringArrayListExtra(EXTRA_FORMATS);
|
||||
if (requested == null || requested.isEmpty()) {
|
||||
requested = new ArrayList<>(java.util.Arrays.asList(DEFAULT_FORMATS));
|
||||
}
|
||||
for (String name : requested) {
|
||||
BarcodeFormat format = toFormat(name);
|
||||
if (format != null) {
|
||||
formats.add(format);
|
||||
}
|
||||
}
|
||||
if (formats.isEmpty()) {
|
||||
formats.add(BarcodeFormat.QR_CODE);
|
||||
}
|
||||
|
||||
Map<DecodeHintType, Object> result = new EnumMap<>(DecodeHintType.class);
|
||||
result.put(DecodeHintType.POSSIBLE_FORMATS, formats);
|
||||
result.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static BarcodeFormat toFormat(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
switch (name) {
|
||||
case "QR_CODE":
|
||||
return BarcodeFormat.QR_CODE;
|
||||
case "CODE_128":
|
||||
return BarcodeFormat.CODE_128;
|
||||
case "CODE_39":
|
||||
return BarcodeFormat.CODE_39;
|
||||
case "EAN_13":
|
||||
return BarcodeFormat.EAN_13;
|
||||
case "EAN_8":
|
||||
return BarcodeFormat.EAN_8;
|
||||
case "UPC_A":
|
||||
return BarcodeFormat.UPC_A;
|
||||
case "ITF":
|
||||
return BarcodeFormat.ITF;
|
||||
case "DATA_MATRIX":
|
||||
return BarcodeFormat.DATA_MATRIX;
|
||||
case "PDF_417":
|
||||
return BarcodeFormat.PDF_417;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 只取 Y plane,按 rowStride 逐行拷贝,交给 zxing 当灰度图 */
|
||||
private static byte[] yuvToLuminance(ImageProxy imageProxy, int width, int height) {
|
||||
ImageProxy.PlaneProxy plane = imageProxy.getPlanes()[0];
|
||||
ByteBuffer buffer = plane.getBuffer();
|
||||
int rowStride = plane.getRowStride();
|
||||
int pixelStride = plane.getPixelStride();
|
||||
|
||||
byte[] data = new byte[width * height];
|
||||
if (1 == pixelStride && rowStride == width) {
|
||||
buffer.get(data, 0, data.length);
|
||||
return data;
|
||||
}
|
||||
|
||||
int offset = 0;
|
||||
for (int row = 0; row < height; row++) {
|
||||
int position = row * rowStride;
|
||||
if (buffer.limit() < position + width) {
|
||||
break;
|
||||
}
|
||||
buffer.position(position);
|
||||
buffer.get(data, offset, width);
|
||||
offset += width;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private static byte[] rotate90(byte[] data, int width, int height, boolean counterClockwise) {
|
||||
byte[] rotated = new byte[data.length];
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
if (counterClockwise) {
|
||||
rotated[(width - 1 - x) * height + y] = data[y * width + x];
|
||||
} else {
|
||||
rotated[x * height + (height - 1 - y)] = data[y * width + x];
|
||||
}
|
||||
}
|
||||
}
|
||||
return rotated;
|
||||
}
|
||||
|
||||
private static byte[] rotate180(byte[] data, int width, int height) {
|
||||
byte[] rotated = new byte[data.length];
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
rotated[(height - 1 - y) * width + (width - 1 - x)] = data[y * width + x];
|
||||
}
|
||||
}
|
||||
return rotated;
|
||||
}
|
||||
|
||||
/** 扫码取景框:半透明遮罩 + 四角高亮 */
|
||||
private static final class FrameOverlay extends View {
|
||||
|
||||
private final Paint dimPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint cornerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final RectF frame = new RectF();
|
||||
private final float density;
|
||||
|
||||
FrameOverlay(android.content.Context context) {
|
||||
super(context);
|
||||
density = context.getResources().getDisplayMetrics().density;
|
||||
dimPaint.setColor(0x66000000);
|
||||
cornerPaint.setColor(0xFF22C55E);
|
||||
cornerPaint.setStyle(Paint.Style.STROKE);
|
||||
cornerPaint.setStrokeWidth(3 * density);
|
||||
cornerPaint.setStrokeCap(Paint.Cap.ROUND);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
super.onDraw(canvas);
|
||||
float size = Math.min(getWidth(), getHeight()) * 0.72f;
|
||||
float left = (getWidth() - size) / 2f;
|
||||
float top = (getHeight() - size) / 2f;
|
||||
frame.set(left, top, left + size, top + size);
|
||||
|
||||
// 四周压暗,中间保持透明
|
||||
canvas.drawRect(0, 0, getWidth(), frame.top, dimPaint);
|
||||
canvas.drawRect(0, frame.bottom, getWidth(), getHeight(), dimPaint);
|
||||
canvas.drawRect(0, frame.top, frame.left, frame.bottom, dimPaint);
|
||||
canvas.drawRect(frame.right, frame.top, getWidth(), frame.bottom, dimPaint);
|
||||
|
||||
float length = size * 0.14f;
|
||||
// 左上
|
||||
canvas.drawLine(frame.left, frame.top, frame.left + length, frame.top, cornerPaint);
|
||||
canvas.drawLine(frame.left, frame.top, frame.left, frame.top + length, cornerPaint);
|
||||
// 右上
|
||||
canvas.drawLine(frame.right - length, frame.top, frame.right, frame.top, cornerPaint);
|
||||
canvas.drawLine(frame.right, frame.top, frame.right, frame.top + length, cornerPaint);
|
||||
// 左下
|
||||
canvas.drawLine(frame.left, frame.bottom - length, frame.left, frame.bottom, cornerPaint);
|
||||
canvas.drawLine(frame.left, frame.bottom, frame.left + length, frame.bottom, cornerPaint);
|
||||
// 右下
|
||||
canvas.drawLine(frame.right - length, frame.bottom, frame.right, frame.bottom, cornerPaint);
|
||||
canvas.drawLine(frame.right, frame.bottom - length, frame.right, frame.bottom, cornerPaint);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
/**
|
||||
* 能力名常量。
|
||||
*
|
||||
* <p>前端通过 {@code getInfo().capabilities} 判断某项能力是否存在,不要靠猜测或 try-catch。
|
||||
* 这里的常量与 {@link NativeKitPlugin#getInfo} 的返回值必须保持一致,新增能力只改这一处。
|
||||
*/
|
||||
public final class Capabilities {
|
||||
|
||||
/** 原生扫码 */
|
||||
public static final String SCAN = "scan";
|
||||
/** 原生拍照 */
|
||||
public static final String CAPTURE = "capture";
|
||||
/** 通用下载器 */
|
||||
public static final String DOWNLOAD = "download";
|
||||
/** 系统分享 */
|
||||
public static final String SHARE = "share";
|
||||
/** 系统打印 */
|
||||
public static final String PRINT = "print";
|
||||
/** 本地通知调度 */
|
||||
public static final String NOTIFY_SCHEDULE = "notify.schedule";
|
||||
/** 已排程任务查询与按归属清理 */
|
||||
public static final String NOTIFY_LIST = "notify.list";
|
||||
/** 通知权限查询与申请 */
|
||||
public static final String NOTIFY_PERMISSION = "notify.permission";
|
||||
/** 精确闹钟授权状态 */
|
||||
public static final String NOTIFY_EXACT = "notify.exact";
|
||||
/** 语音输入 */
|
||||
public static final String VOICE = "voice";
|
||||
/** 生物识别 */
|
||||
public static final String BIOMETRIC = "biometric";
|
||||
/** 加密会话存储 */
|
||||
public static final String SESSION = "session";
|
||||
/** 蓝牙 ESC/POS 打印 */
|
||||
public static final String BT_PRINT = "btPrint";
|
||||
/** SAF 文件选择与另存 */
|
||||
public static final String SAF = "saf";
|
||||
/** 系统日历日程写入 */
|
||||
public static final String CALENDAR = "calendar";
|
||||
/** 前台/后台状态事件 */
|
||||
public static final String APP_STATE = "app.state";
|
||||
/** 网络状态查询与事件 */
|
||||
public static final String APP_NETWORK = "app.network";
|
||||
/** 权限状态查询与系统设置跳转 */
|
||||
public static final String APP_PERMISSION = "app.permission";
|
||||
/** 设备标识、响铃模式、常亮、方向、重启、清缓存 */
|
||||
public static final String APP_DEVICE = "app.device";
|
||||
/** 通讯录批量写入 */
|
||||
public static final String CONTACTS = "contacts";
|
||||
/** 震动、剪贴板、设备信息 */
|
||||
public static final String MISC = "misc";
|
||||
|
||||
private Capabilities() {
|
||||
}
|
||||
|
||||
/** 当前壳支持的全部能力 */
|
||||
public static String[] all() {
|
||||
return new String[] {
|
||||
SCAN,
|
||||
CAPTURE,
|
||||
DOWNLOAD,
|
||||
SHARE,
|
||||
PRINT,
|
||||
NOTIFY_SCHEDULE,
|
||||
NOTIFY_LIST,
|
||||
NOTIFY_PERMISSION,
|
||||
NOTIFY_EXACT,
|
||||
VOICE,
|
||||
BIOMETRIC,
|
||||
SESSION,
|
||||
BT_PRINT,
|
||||
SAF,
|
||||
CALENDAR,
|
||||
APP_STATE,
|
||||
APP_NETWORK,
|
||||
APP_PERMISSION,
|
||||
APP_DEVICE,
|
||||
CONTACTS,
|
||||
MISC
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.ContentProviderOperation;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.ContentUris;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.provider.ContactsContract;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.getcapacitor.JSArray;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 通讯录批量写入。
|
||||
*
|
||||
* <p>存在的意义只有一个:让系统语音助手和来电识别能拿到客户姓名与号码。
|
||||
* 业务数据永远在 App 里,助手读不到。
|
||||
*
|
||||
* <p>业务 ID 存在自定义 MIMETYPE 的 Data 行里,不占姓名、备注、昵称任何可见字段,
|
||||
* 通讯录界面不会显示这一行。靠它做增量更新与删除,而不是靠姓名匹配 —— 改名就失效。
|
||||
*/
|
||||
final class ContactsHelper {
|
||||
|
||||
/** 自定义 mimetype,通讯录 App 不认识,因此不会渲染 */
|
||||
private static final String PROFILE_MIMETYPE = "vnd.android.cursor.item/com.imyeyu.gao.customer.profile";
|
||||
private static final String DEFAULT_GROUP = "GaoCustomer";
|
||||
private static final int BATCH_SIZE = 100;
|
||||
private static final String SAFE_PHONE = "[+\\d][\\d\\-\\s]{4,24}";
|
||||
|
||||
private ContactsHelper() {
|
||||
}
|
||||
|
||||
// ---------- 探测 ----------
|
||||
|
||||
static void available(Context context, PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
boolean granted = hasPermission(context);
|
||||
result.put("hasPermission", granted);
|
||||
result.put("canWrite", granted);
|
||||
result.put("total", granted ? countOwned(context, null) : 0);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---------- 单条 ----------
|
||||
|
||||
static void add(Context context, PluginCall call) {
|
||||
String name = call.getString("name");
|
||||
String phone = call.getString("phone");
|
||||
if (name == null || name.trim().isEmpty() || phone == null || !phone.matches(SAFE_PHONE)) {
|
||||
call.reject("姓名或手机号不合法", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
String businessId = call.getString("businessId", "");
|
||||
String group = normalizeGroup(call.getString("groupTag"));
|
||||
String note = call.getString("note");
|
||||
|
||||
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
|
||||
int rawIndex = operations.size();
|
||||
operations.add(newRawContactOperation());
|
||||
operations.add(buildNameOperation(rawIndex, name.trim()));
|
||||
operations.add(buildPhoneOperation(rawIndex, phone.trim()));
|
||||
operations.add(buildProfileOperation(rawIndex, businessId, group));
|
||||
if (note != null && !note.isEmpty()) {
|
||||
operations.add(buildNoteOperation(rawIndex, note));
|
||||
}
|
||||
|
||||
try {
|
||||
android.content.ContentProviderResult[] results = context
|
||||
.getContentResolver()
|
||||
.applyBatch(ContactsContract.AUTHORITY, operations);
|
||||
long rawContactId = results[0].uri == null ? 0 : ContentUris.parseId(results[0].uri);
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("rawContactId", rawContactId);
|
||||
call.resolve(result);
|
||||
} catch (Exception error) {
|
||||
call.reject("写入通讯录失败:" + error.getMessage(), "insert_failed");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 批量同步 ----------
|
||||
|
||||
/**
|
||||
* 批量幂等同步。
|
||||
*
|
||||
* <p>以 businessId 为准做差集:没有的插入、变了且更新、多出来的删除。
|
||||
* 同一个 groupTag 下的历史数据会被完整对齐,不会残留脏号码。
|
||||
*/
|
||||
static void sync(Context context, PluginCall call) {
|
||||
JSArray items = call.getArray("items");
|
||||
if (items == null) {
|
||||
call.reject("缺少 items", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
String group = normalizeGroup(call.getString("groupTag"));
|
||||
Map<String, Long> existing = queryOwned(context, group);
|
||||
|
||||
List<Item> toInsert = new ArrayList<>();
|
||||
List<Item> toUpdate = new ArrayList<>();
|
||||
Set<String> incoming = new HashSet<>();
|
||||
|
||||
for (int index = 0; index < items.length(); index++) {
|
||||
org.json.JSONObject raw = items.optJSONObject(index);
|
||||
if (raw == null) {
|
||||
continue;
|
||||
}
|
||||
String name = raw.optString("name", null);
|
||||
String phone = raw.optString("phone", null);
|
||||
String businessId = raw.optString("id", null);
|
||||
if (businessId == null || businessId.isEmpty() || name == null || name.trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (phone == null || !phone.matches(SAFE_PHONE)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
incoming.add(businessId);
|
||||
Item item = new Item();
|
||||
item.businessId = businessId;
|
||||
item.name = name.trim();
|
||||
item.phone = phone.trim();
|
||||
item.note = raw.optString("note", null);
|
||||
|
||||
Long rawContactId = existing.get(businessId);
|
||||
if (rawContactId == null) {
|
||||
toInsert.add(item);
|
||||
} else {
|
||||
item.rawContactId = rawContactId;
|
||||
toUpdate.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
List<Long> toDelete = new ArrayList<>();
|
||||
for (Map.Entry<String, Long> entry : existing.entrySet()) {
|
||||
if (!incoming.contains(entry.getKey())) {
|
||||
toDelete.add(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
int inserted = 0;
|
||||
int updated = 0;
|
||||
int deleted = 0;
|
||||
|
||||
try {
|
||||
ContentResolver resolver = context.getContentResolver();
|
||||
deleted = deleteRawContacts(resolver, toDelete);
|
||||
updated = updateContacts(context, toUpdate);
|
||||
inserted = insertContacts(context, toInsert, group);
|
||||
} catch (Exception error) {
|
||||
call.reject("同步通讯录失败:" + error.getMessage(), "sync_failed");
|
||||
return;
|
||||
}
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("inserted", inserted);
|
||||
result.put("updated", updated);
|
||||
result.put("deleted", deleted);
|
||||
result.put("total", countOwned(context, group));
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
static void clear(Context context, PluginCall call) {
|
||||
String group = call.getString("groupTag") == null ? null : normalizeGroup(call.getString("groupTag"));
|
||||
Map<String, Long> existing = queryOwned(context, group);
|
||||
try {
|
||||
int deleted = deleteRawContacts(context.getContentResolver(), new ArrayList<>(existing.values()));
|
||||
JSObject result = new JSObject();
|
||||
result.put("deleted", deleted);
|
||||
call.resolve(result);
|
||||
} catch (Exception error) {
|
||||
call.reject("清除通讯录失败:" + error.getMessage(), "delete_failed");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 内部 ----------
|
||||
|
||||
private static int insertContacts(Context context, List<Item> items, String group) throws Exception {
|
||||
if (items.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
ContentResolver resolver = context.getContentResolver();
|
||||
int inserted = 0;
|
||||
|
||||
for (int offset = 0; offset < items.size(); offset += BATCH_SIZE) {
|
||||
List<Item> slice = items.subList(offset, Math.min(offset + BATCH_SIZE, items.size()));
|
||||
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
|
||||
|
||||
for (Item item : slice) {
|
||||
int rawIndex = operations.size();
|
||||
operations.add(newRawContactOperation());
|
||||
operations.add(buildNameOperation(rawIndex, item.name));
|
||||
operations.add(buildPhoneOperation(rawIndex, item.phone));
|
||||
operations.add(buildProfileOperation(rawIndex, item.businessId, group));
|
||||
if (item.note != null && !item.note.isEmpty()) {
|
||||
operations.add(buildNoteOperation(rawIndex, item.note));
|
||||
}
|
||||
}
|
||||
|
||||
resolver.applyBatch(ContactsContract.AUTHORITY, operations);
|
||||
inserted += slice.size();
|
||||
}
|
||||
return inserted;
|
||||
}
|
||||
|
||||
private static int updateContacts(Context context, List<Item> items) throws Exception {
|
||||
if (items.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
ContentResolver resolver = context.getContentResolver();
|
||||
int updated = 0;
|
||||
|
||||
for (int offset = 0; offset < items.size(); offset += BATCH_SIZE) {
|
||||
List<Item> slice = items.subList(offset, Math.min(offset + BATCH_SIZE, items.size()));
|
||||
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
|
||||
|
||||
for (Item item : slice) {
|
||||
String rawId = String.valueOf(item.rawContactId);
|
||||
operations.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||
.withSelection(
|
||||
ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
|
||||
new String[] { rawId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }
|
||||
)
|
||||
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, item.name)
|
||||
.build());
|
||||
operations.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
|
||||
.withSelection(
|
||||
ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
|
||||
new String[] { rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }
|
||||
)
|
||||
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, item.phone)
|
||||
.build());
|
||||
}
|
||||
|
||||
resolver.applyBatch(ContactsContract.AUTHORITY, operations);
|
||||
updated += slice.size();
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
private static int deleteRawContacts(ContentResolver resolver, List<Long> rawContactIds) throws Exception {
|
||||
if (rawContactIds.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
int deleted = 0;
|
||||
for (int offset = 0; offset < rawContactIds.size(); offset += BATCH_SIZE) {
|
||||
List<Long> slice = rawContactIds.subList(offset, Math.min(offset + BATCH_SIZE, rawContactIds.size()));
|
||||
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
|
||||
for (Long rawContactId : slice) {
|
||||
operations.add(ContentProviderOperation.newDelete(
|
||||
ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId)
|
||||
).build());
|
||||
}
|
||||
resolver.applyBatch(ContactsContract.AUTHORITY, operations);
|
||||
deleted += slice.size();
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建 RawContact。
|
||||
*
|
||||
* <p>ACCOUNT_TYPE / ACCOUNT_NAME 必须显式写 null:不写和写 null 在 AOSP 上等价,
|
||||
* 但部分 ROM 的 ContactsProvider 会因此拒绝插入或归到奇怪的账户下。
|
||||
*/
|
||||
private static ContentProviderOperation newRawContactOperation() {
|
||||
return ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
|
||||
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
|
||||
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static ContentProviderOperation buildNameOperation(int rawIndex, String name) {
|
||||
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
|
||||
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
|
||||
.withValue(
|
||||
ContactsContract.Data.MIMETYPE,
|
||||
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
|
||||
)
|
||||
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static ContentProviderOperation buildPhoneOperation(int rawIndex, String phone) {
|
||||
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
|
||||
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
|
||||
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
|
||||
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
|
||||
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static ContentProviderOperation buildProfileOperation(int rawIndex, String businessId, String group) {
|
||||
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
|
||||
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
|
||||
.withValue(ContactsContract.Data.MIMETYPE, PROFILE_MIMETYPE)
|
||||
.withValue(ContactsContract.Data.DATA1, businessId)
|
||||
.withValue(ContactsContract.Data.DATA2, group)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static ContentProviderOperation buildNoteOperation(int rawIndex, String note) {
|
||||
return ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
|
||||
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawIndex)
|
||||
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
|
||||
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** 查出本 App 写入的联系人:businessId -> rawContactId */
|
||||
private static Map<String, Long> queryOwned(Context context, String group) {
|
||||
Map<String, Long> result = new HashMap<>();
|
||||
String[] projection = {
|
||||
ContactsContract.Data.RAW_CONTACT_ID,
|
||||
ContactsContract.Data.DATA1
|
||||
};
|
||||
String selection = ContactsContract.Data.MIMETYPE + "=?";
|
||||
List<String> args = new ArrayList<>();
|
||||
args.add(PROFILE_MIMETYPE);
|
||||
if (group != null) {
|
||||
selection += " AND " + ContactsContract.Data.DATA2 + "=?";
|
||||
args.add(group);
|
||||
}
|
||||
|
||||
try (Cursor cursor = context.getContentResolver().query(
|
||||
ContactsContract.Data.CONTENT_URI,
|
||||
projection,
|
||||
selection,
|
||||
args.toArray(new String[0]),
|
||||
null
|
||||
)) {
|
||||
if (cursor == null) {
|
||||
return result;
|
||||
}
|
||||
while (cursor.moveToNext()) {
|
||||
String businessId = cursor.getString(1);
|
||||
if (businessId != null && !businessId.isEmpty()) {
|
||||
result.put(businessId, cursor.getLong(0));
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 读取失败按空处理,下次同步会重来
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int countOwned(Context context, String group) {
|
||||
return queryOwned(context, group).size();
|
||||
}
|
||||
|
||||
private static boolean hasPermission(Context context) {
|
||||
return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
|
||||
== PackageManager.PERMISSION_GRANTED
|
||||
&& ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS)
|
||||
== PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
private static String normalizeGroup(String group) {
|
||||
if (group == null || group.trim().isEmpty()) {
|
||||
return DEFAULT_GROUP;
|
||||
}
|
||||
// DATA2 只用来分组,限制长度避免异常输入撑爆字段
|
||||
String trimmed = group.trim();
|
||||
return 40 < trimmed.length() ? trimmed.substring(0, 40) : trimmed;
|
||||
}
|
||||
|
||||
private static final class Item {
|
||||
String businessId;
|
||||
String name;
|
||||
String phone;
|
||||
String note;
|
||||
long rawContactId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.app.DownloadManager;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.Environment;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* 通用下载器。
|
||||
*
|
||||
* <p>WebView 里的 {@code a[download]} 对跨域地址无效,数据导出的 ZIP 在 App 内要么跳到系统浏览器
|
||||
* 要么静默失败。这里走系统 DownloadManager:断点续传、通知栏进度、断电重连都由系统负责。
|
||||
*
|
||||
* <p>下载完成后额外复制一份到 cache,返回 {@code file://} 路径 —— Downloads 里的文件不在
|
||||
* FileProvider 放行范围内,直接分享或打印会失败。
|
||||
*/
|
||||
final class DownloadHelper {
|
||||
|
||||
private static final long TIMEOUT_MS = 10 * 60 * 1000L;
|
||||
private static final String CACHE_DIR = "nativekit-download";
|
||||
private static final String DEFAULT_SUB_DIR = "GaoCustomer";
|
||||
private static final String SAFE_NAME = "[\\w.\\-]{1,120}";
|
||||
|
||||
private DownloadHelper() {
|
||||
}
|
||||
|
||||
static void download(Plugin plugin, PluginCall call) {
|
||||
Context context = plugin.getContext();
|
||||
String url = call.getString("url");
|
||||
String fileName = call.getString("fileName");
|
||||
String subDir = call.getString("subDir", DEFAULT_SUB_DIR);
|
||||
boolean showNotification = !Boolean.FALSE.equals(call.getBoolean("notify", true));
|
||||
|
||||
if (url == null || !(url.startsWith("https://") || url.startsWith("http://"))) {
|
||||
call.reject("下载地址必须是 http 或 https", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
if (fileName == null || !fileName.matches(SAFE_NAME)) {
|
||||
call.reject("文件名不合法", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
if (subDir == null || !subDir.matches(SAFE_NAME)) {
|
||||
call.reject("子目录名不合法", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
|
||||
if (manager == null) {
|
||||
call.reject("下载服务不可用", "service_unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
|
||||
request.setTitle(fileName);
|
||||
request.setDescription(subDir);
|
||||
request.setAllowedOverMetered(true);
|
||||
request.setAllowedOverRoaming(false);
|
||||
request.setNotificationVisibility(
|
||||
showNotification
|
||||
? DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
|
||||
: DownloadManager.Request.VISIBILITY_HIDDEN
|
||||
);
|
||||
request.setDestinationInExternalPublicDir(
|
||||
Environment.DIRECTORY_DOWNLOADS,
|
||||
subDir + "/" + fileName
|
||||
);
|
||||
|
||||
long downloadId;
|
||||
try {
|
||||
downloadId = manager.enqueue(request);
|
||||
} catch (Exception error) {
|
||||
call.reject("无法发起下载:" + error.getMessage(), "enqueue_failed");
|
||||
return;
|
||||
}
|
||||
|
||||
Handler handler = new Handler(Looper.getMainLooper());
|
||||
final BroadcastReceiver[] holder = new BroadcastReceiver[1];
|
||||
final boolean[] settled = new boolean[1];
|
||||
|
||||
Runnable timeout = () -> {
|
||||
if (settled[0]) {
|
||||
return;
|
||||
}
|
||||
settled[0] = true;
|
||||
unregister(context, holder[0]);
|
||||
call.reject("下载超时", "timeout");
|
||||
};
|
||||
|
||||
BroadcastReceiver receiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context receiverContext, Intent intent) {
|
||||
if (intent == null) {
|
||||
return;
|
||||
}
|
||||
long completed = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
|
||||
if (completed != downloadId || settled[0]) {
|
||||
return;
|
||||
}
|
||||
settled[0] = true;
|
||||
handler.removeCallbacks(timeout);
|
||||
unregister(receiverContext, holder[0]);
|
||||
resolveResult(call, manager, downloadId, fileName, context);
|
||||
}
|
||||
};
|
||||
holder[0] = receiver;
|
||||
|
||||
ContextCompat.registerReceiver(
|
||||
context,
|
||||
receiver,
|
||||
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE),
|
||||
ContextCompat.RECEIVER_EXPORTED
|
||||
);
|
||||
handler.postDelayed(timeout, TIMEOUT_MS);
|
||||
}
|
||||
|
||||
private static void resolveResult(
|
||||
PluginCall call,
|
||||
DownloadManager manager,
|
||||
long downloadId,
|
||||
String fileName,
|
||||
Context context
|
||||
) {
|
||||
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
|
||||
long size = 0;
|
||||
int status = DownloadManager.STATUS_FAILED;
|
||||
String reason = "";
|
||||
|
||||
try (Cursor cursor = manager.query(query)) {
|
||||
if (cursor != null && cursor.moveToFirst()) {
|
||||
status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
|
||||
size = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
|
||||
reason = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON));
|
||||
}
|
||||
} catch (Exception error) {
|
||||
call.reject("无法读取下载结果", "query_failed");
|
||||
return;
|
||||
}
|
||||
|
||||
if (status != DownloadManager.STATUS_SUCCESSFUL) {
|
||||
call.reject("下载失败,状态 " + status + ",原因 " + reason, "download_failed");
|
||||
return;
|
||||
}
|
||||
|
||||
File cached = copyToCache(context, manager, downloadId, fileName);
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("name", fileName);
|
||||
result.put("size", 0 < size ? size : (cached == null ? 0 : cached.length()));
|
||||
result.put("path", cached == null ? "" : "file://" + cached.getAbsolutePath());
|
||||
result.put("uri", String.valueOf(manager.getUriForDownloadedFile(downloadId)));
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制到 cache。
|
||||
*
|
||||
* <p>不能用 {@code Environment.getExternalStoragePublicDirectory()} 拼绝对路径去读:
|
||||
* Android 10 起 Downloads 属于分区存储,直接 {@code FileInputStream} 会失败。
|
||||
* {@code openDownloadedFile} 拿 ParcelFileDescriptor 是官方通道,各版本都通。
|
||||
*/
|
||||
private static File copyToCache(Context context, DownloadManager manager, long downloadId, String fileName) {
|
||||
File directory = new File(context.getCacheDir(), CACHE_DIR);
|
||||
if (!directory.exists() && !directory.mkdirs()) {
|
||||
return null;
|
||||
}
|
||||
File target = new File(directory, fileName);
|
||||
|
||||
try (ParcelFileDescriptor descriptor = manager.openDownloadedFile(downloadId)) {
|
||||
if (descriptor == null) {
|
||||
return null;
|
||||
}
|
||||
try (InputStream input = new FileInputStream(descriptor.getFileDescriptor());
|
||||
OutputStream output = new FileOutputStream(target)) {
|
||||
byte[] buffer = new byte[32768];
|
||||
int read;
|
||||
while ((read = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, read);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
} catch (Exception error) {
|
||||
// 复制失败不算致命,前端还能拿 content:// 走系统分享
|
||||
target.delete();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void unregister(Context context, BroadcastReceiver receiver) {
|
||||
if (receiver == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
context.unregisterReceiver(receiver);
|
||||
} catch (Exception ignored) {
|
||||
// 已注销或进程重建,忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.content.Context;
|
||||
import android.webkit.MimeTypeMap;
|
||||
|
||||
import com.getcapacitor.JSArray;
|
||||
import com.getcapacitor.JSObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 相机、SAF 等能力共用的文件信息结构。
|
||||
*
|
||||
* <p>返回给 Web 的路径统一是 {@code file://} 形式,前端需经 {@code Capacitor.convertFileSrc()}
|
||||
* 才能放进 img/fetch 使用。
|
||||
*/
|
||||
final class MediaInfo {
|
||||
|
||||
private MediaInfo() {
|
||||
}
|
||||
|
||||
/** 把绝对路径列表组装成 { files: [...] } */
|
||||
static JSObject buildFiles(Context context, List<String> paths) {
|
||||
JSArray files = new JSArray();
|
||||
if (paths != null) {
|
||||
for (String path : paths) {
|
||||
if (path == null || path.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
File file = new File(stripScheme(path));
|
||||
if (!file.exists()) {
|
||||
continue;
|
||||
}
|
||||
JSObject item = new JSObject();
|
||||
item.put("path", "file://" + file.getAbsolutePath());
|
||||
item.put("name", file.getName());
|
||||
item.put("size", file.length());
|
||||
item.put("mimeType", guessMimeType(file.getName()));
|
||||
files.put(item);
|
||||
}
|
||||
}
|
||||
JSObject result = new JSObject();
|
||||
result.put("files", files);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 单个文件的描述 */
|
||||
static JSObject buildFile(String path) {
|
||||
File file = new File(stripScheme(path));
|
||||
JSObject item = new JSObject();
|
||||
item.put("path", "file://" + file.getAbsolutePath());
|
||||
item.put("name", file.getName());
|
||||
item.put("size", file.length());
|
||||
item.put("mimeType", guessMimeType(file.getName()));
|
||||
return item;
|
||||
}
|
||||
|
||||
static String stripScheme(String path) {
|
||||
if (path.startsWith("file://")) {
|
||||
return path.substring("file://".length());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
static String guessMimeType(String fileName) {
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
if (0 < dot) {
|
||||
String extension = fileName.substring(dot + 1).toLowerCase(Locale.ROOT);
|
||||
String guess = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
|
||||
if (guess != null) {
|
||||
return guess;
|
||||
}
|
||||
if ("jpg".equals(extension) || "jpeg".equals(extension)) {
|
||||
return "image/jpeg";
|
||||
}
|
||||
if ("pdf".equals(extension)) {
|
||||
return "application/pdf";
|
||||
}
|
||||
}
|
||||
return "application/octet-stream";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,929 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.ClipData;
|
||||
import android.content.ClipboardManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.VibrationEffect;
|
||||
import android.os.Vibrator;
|
||||
import android.os.VibratorManager;
|
||||
import android.provider.Settings;
|
||||
import android.webkit.WebSettings;
|
||||
|
||||
import androidx.activity.result.ActivityResult;
|
||||
|
||||
import com.getcapacitor.JSArray;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.PermissionState;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.getcapacitor.PluginMethod;
|
||||
import com.getcapacitor.annotation.ActivityCallback;
|
||||
import com.getcapacitor.annotation.CapacitorPlugin;
|
||||
import com.getcapacitor.annotation.Permission;
|
||||
import com.getcapacitor.annotation.PermissionCallback;
|
||||
import com.imyeyu.gao.customer.MainActivity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 原生能力网关。
|
||||
*
|
||||
* <p>所有能力收在一个插件下,避免为每个小功能单独注册插件。前端通过 {@link #getInfo()}
|
||||
* 拿能力表做降级判断,不要靠 try-catch 猜。
|
||||
*
|
||||
* <p>约定:方法失败时 {@code reject(message, code)},成功时 {@code resolve(JSObject)}。
|
||||
*/
|
||||
@CapacitorPlugin(
|
||||
name = "NativeKit",
|
||||
permissions = {
|
||||
@Permission(alias = "camera", strings = { Manifest.permission.CAMERA }),
|
||||
@Permission(alias = "microphone", strings = { Manifest.permission.RECORD_AUDIO }),
|
||||
@Permission(alias = "notifications", strings = { Manifest.permission.POST_NOTIFICATIONS }),
|
||||
@Permission(
|
||||
alias = "calendar",
|
||||
strings = { Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR }
|
||||
),
|
||||
@Permission(
|
||||
alias = "contacts",
|
||||
strings = { Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS }
|
||||
),
|
||||
@Permission(
|
||||
alias = "bluetooth",
|
||||
strings = { Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN }
|
||||
)
|
||||
}
|
||||
)
|
||||
public class NativeKitPlugin extends Plugin {
|
||||
|
||||
/** 通知点击后待消费的路由,键名与 MainActivity 共用 */
|
||||
public static final String PREFS = "nativekit";
|
||||
public static final String KEY_LAUNCH_ROUTE = "launch_route";
|
||||
|
||||
private NotificationScheduler notificationScheduler;
|
||||
private VoiceInput voiceInput;
|
||||
private SystemHelper systemHelper;
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
notificationScheduler = new NotificationScheduler(getContext());
|
||||
voiceInput = new VoiceInput(this);
|
||||
systemHelper = new SystemHelper(this);
|
||||
systemHelper.start();
|
||||
NotificationScheduler.ensureChannels(getContext());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleOnDestroy() {
|
||||
if (voiceInput != null) {
|
||||
voiceInput.release();
|
||||
}
|
||||
if (systemHelper != null) {
|
||||
systemHelper.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/** 供内部 helper 派发事件,notifyListeners 是 protected */
|
||||
void emit(String event, JSObject payload) {
|
||||
notifyListeners(event, payload);
|
||||
}
|
||||
|
||||
// ---------- 能力协商 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void getInfo(PluginCall call) {
|
||||
call.resolve(buildInfo(getContext()));
|
||||
}
|
||||
|
||||
/** 供插件与 MainActivity 共用,避免两处各写一份 */
|
||||
public static JSObject buildInfo(Context context) {
|
||||
JSObject info = new JSObject();
|
||||
try {
|
||||
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
|
||||
info.put("versionCode", Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
|
||||
? packageInfo.getLongVersionCode()
|
||||
: packageInfo.versionCode);
|
||||
info.put("versionName", packageInfo.versionName == null ? "" : packageInfo.versionName);
|
||||
} catch (Exception error) {
|
||||
info.put("versionCode", 0);
|
||||
info.put("versionName", "");
|
||||
}
|
||||
info.put("packageName", context.getPackageName());
|
||||
info.put("sdkInt", Build.VERSION.SDK_INT);
|
||||
info.put("webViewVersion", resolveWebViewVersion(context));
|
||||
info.put("capabilities", JSArray.from(Capabilities.all()));
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 冷启动时取走通知带来的路由。
|
||||
*
|
||||
* <p>取走即清除,避免下次冷启动重复跳转。
|
||||
*/
|
||||
@PluginMethod
|
||||
public void getLaunchRoute(PluginCall call) {
|
||||
SharedPreferences preferences = getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
String route = preferences.getString(KEY_LAUNCH_ROUTE, null);
|
||||
if (route != null) {
|
||||
preferences.edit().remove(KEY_LAUNCH_ROUTE).apply();
|
||||
}
|
||||
JSObject result = new JSObject();
|
||||
result.put("route", route == null ? JSObject.NULL : route);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---------- 扫码 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void scan(PluginCall call) {
|
||||
if (getPermissionState("camera") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("camera", call, "scanWithPermission");
|
||||
return;
|
||||
}
|
||||
startScan(call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void scanWithPermission(PluginCall call) {
|
||||
if (getPermissionState("camera") != PermissionState.GRANTED) {
|
||||
call.reject("未授予相机权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
startScan(call);
|
||||
}
|
||||
|
||||
private void startScan(PluginCall call) {
|
||||
Intent intent = new Intent(getContext(), CameraKitActivity.class);
|
||||
intent.putExtra(CameraKitActivity.EXTRA_MODE, CameraKitActivity.MODE_SCAN);
|
||||
intent.putExtra(CameraKitActivity.EXTRA_TORCH, Boolean.TRUE.equals(call.getBoolean("torch", false)));
|
||||
intent.putExtra(
|
||||
CameraKitActivity.EXTRA_CONTINUOUS,
|
||||
Boolean.TRUE.equals(call.getBoolean("continuous", false))
|
||||
);
|
||||
JSArray formats = call.getArray("formats");
|
||||
if (formats != null && formats.length() != 0) {
|
||||
intent.putStringArrayListExtra(
|
||||
CameraKitActivity.EXTRA_FORMATS,
|
||||
new ArrayList<>(toStringList(formats))
|
||||
);
|
||||
}
|
||||
startActivityForResult(call, intent, "scanResult");
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
private void scanResult(PluginCall call, ActivityResult result) {
|
||||
if (call == null) {
|
||||
return;
|
||||
}
|
||||
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
|
||||
call.reject("已取消扫码", "cancelled");
|
||||
return;
|
||||
}
|
||||
Intent data = result.getData();
|
||||
JSObject payload = new JSObject();
|
||||
payload.put("text", data == null ? "" : safeString(data.getStringExtra(CameraKitActivity.RESULT_TEXT)));
|
||||
payload.put("format", data == null ? "" : safeString(data.getStringExtra(CameraKitActivity.RESULT_FORMAT)));
|
||||
call.resolve(payload);
|
||||
}
|
||||
|
||||
// ---------- 拍照 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void capture(PluginCall call) {
|
||||
if (getPermissionState("camera") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("camera", call, "captureWithPermission");
|
||||
return;
|
||||
}
|
||||
startCapture(call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void captureWithPermission(PluginCall call) {
|
||||
if (getPermissionState("camera") != PermissionState.GRANTED) {
|
||||
call.reject("未授予相机权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
startCapture(call);
|
||||
}
|
||||
|
||||
private void startCapture(PluginCall call) {
|
||||
Intent intent = new Intent(getContext(), CameraKitActivity.class);
|
||||
intent.putExtra(CameraKitActivity.EXTRA_MODE, CameraKitActivity.MODE_CAPTURE);
|
||||
intent.putExtra(
|
||||
CameraKitActivity.EXTRA_MULTIPLE,
|
||||
Boolean.TRUE.equals(call.getBoolean("multiple", false))
|
||||
);
|
||||
intent.putExtra(CameraKitActivity.EXTRA_MAX_COUNT, toInt(call.getInt("maxCount"), 9));
|
||||
intent.putExtra(
|
||||
CameraKitActivity.EXTRA_FACING,
|
||||
"front".equals(call.getString("facing")) ? CameraKitActivity.FACING_FRONT : CameraKitActivity.FACING_BACK
|
||||
);
|
||||
intent.putExtra(CameraKitActivity.EXTRA_FLASH, Boolean.TRUE.equals(call.getBoolean("flash", false)));
|
||||
startActivityForResult(call, intent, "captureResult");
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
private void captureResult(PluginCall call, ActivityResult result) {
|
||||
if (call == null) {
|
||||
return;
|
||||
}
|
||||
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
|
||||
call.reject("已取消拍照", "cancelled");
|
||||
return;
|
||||
}
|
||||
Intent data = result.getData();
|
||||
ArrayList<String> paths = data == null
|
||||
? new ArrayList<>()
|
||||
: data.getStringArrayListExtra(CameraKitActivity.RESULT_FILES);
|
||||
call.resolve(MediaInfo.buildFiles(getContext(), paths));
|
||||
}
|
||||
|
||||
// ---------- 下载 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void download(PluginCall call) {
|
||||
DownloadHelper.download(this, call);
|
||||
}
|
||||
|
||||
// ---------- 分享 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void share(PluginCall call) {
|
||||
String path = call.getString("path");
|
||||
if (path == null || path.isEmpty()) {
|
||||
call.reject("缺少文件路径", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
ShareHelper.share(getActivity(), call, path);
|
||||
}
|
||||
|
||||
// ---------- 打印 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void print(PluginCall call) {
|
||||
JSArray paths = call.getArray("paths");
|
||||
if (paths == null || paths.length() == 0) {
|
||||
call.reject("缺少待打印文件", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
PrintHelper.print(getActivity(), call, toStringList(paths), call.getString("jobName", "打印"));
|
||||
}
|
||||
|
||||
// ---------- 本地通知 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void scheduleNotification(PluginCall call) {
|
||||
notificationScheduler.schedule(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void cancelNotification(PluginCall call) {
|
||||
Integer id = call.getInt("id");
|
||||
if (id == null) {
|
||||
call.reject("缺少通知 id", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
notificationScheduler.cancel(id);
|
||||
JSObject result = new JSObject();
|
||||
result.put("id", id);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void cancelAllNotifications(PluginCall call) {
|
||||
notificationScheduler.cancelAll(call.getString("owner"));
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
/** 列出已排程的通知任务,用于诊断与共用设备上的账号隔离 */
|
||||
@PluginMethod
|
||||
public void listScheduledNotifications(PluginCall call) {
|
||||
notificationScheduler.list(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void getNotificationPermission(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("granted", NotificationScheduler.hasNotificationPermission(getContext()));
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 申请通知权限。
|
||||
*
|
||||
* <p>POST_NOTIFICATIONS 是 API 33 才引入的,低版本直接视为已授予,
|
||||
* 不能走 @Permission 注解,否则在 Android 12 上会永远返回拒绝。
|
||||
*/
|
||||
@PluginMethod
|
||||
public void requestNotificationPermission(PluginCall call) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("granted", true);
|
||||
call.resolve(result);
|
||||
return;
|
||||
}
|
||||
if (NotificationScheduler.hasNotificationPermission(getContext())) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("granted", true);
|
||||
call.resolve(result);
|
||||
return;
|
||||
}
|
||||
requestPermissionForAlias("notifications", call, "notificationPermissionResult");
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void notificationPermissionResult(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("granted", NotificationScheduler.hasNotificationPermission(getContext()));
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void canScheduleExactAlarms(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("granted", NotificationScheduler.canScheduleExactAlarms(getContext()));
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void openExactAlarmSettings(PluginCall call) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
|
||||
call.resolve();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
|
||||
intent.setData(Uri.parse("package:" + getContext().getPackageName()));
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
getContext().startActivity(intent);
|
||||
call.resolve();
|
||||
} catch (Exception error) {
|
||||
call.reject("无法打开精确闹钟设置", "activity_not_found");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 语音 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void voiceAvailable(PluginCall call) {
|
||||
voiceInput.available(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void voiceStart(PluginCall call) {
|
||||
voiceInput.start(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void voiceStop(PluginCall call) {
|
||||
voiceInput.stop(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void voiceCancel(PluginCall call) {
|
||||
voiceInput.cancel(call);
|
||||
}
|
||||
|
||||
/** 语音 Intent 通道的启动入口,VoiceInput 不持有 Activity 能力 */
|
||||
void startVoiceIntent(PluginCall call, Intent intent) {
|
||||
startActivityForResult(call, intent, "voiceIntentResult");
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void voicePermissionResult(PluginCall call) {
|
||||
voiceInput.onPermissionResult(call);
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
private void voiceIntentResult(PluginCall call, ActivityResult result) {
|
||||
voiceInput.onIntentResult(call, result);
|
||||
}
|
||||
|
||||
/** 由 VoiceInput 回调,交给能力协商与权限流程使用 */
|
||||
boolean hasMicrophonePermission() {
|
||||
return getPermissionState("microphone") == PermissionState.GRANTED;
|
||||
}
|
||||
|
||||
void requestMicrophonePermission(PluginCall call, String callbackName) {
|
||||
requestPermissionForAlias("microphone", call, callbackName);
|
||||
}
|
||||
|
||||
/** 语音 Intent 通道返回时压了一层 Activity,用它标记内部导航 */
|
||||
void markInternalNavigation() {
|
||||
MainActivity.markInternalNavigation();
|
||||
}
|
||||
|
||||
void emitVoicePartial(String text) {
|
||||
JSObject payload = new JSObject();
|
||||
payload.put("text", text);
|
||||
notifyListeners("voicePartial", payload);
|
||||
}
|
||||
|
||||
void emitVoiceState(String state) {
|
||||
JSObject payload = new JSObject();
|
||||
payload.put("state", state);
|
||||
notifyListeners("voiceState", payload);
|
||||
}
|
||||
|
||||
// ---------- 生物识别与会话 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void biometricAvailable(PluginCall call) {
|
||||
// BiometricPrompt 内部要操作 FragmentManager,必须在主线程
|
||||
getActivity().runOnUiThread(() -> BiometricHelper.available(getActivity(), call));
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void biometricUnlock(PluginCall call) {
|
||||
getActivity().runOnUiThread(() -> BiometricHelper.unlock(getActivity(), call));
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void saveSession(PluginCall call) {
|
||||
String json = call.getString("json");
|
||||
if (json == null) {
|
||||
call.reject("缺少会话内容", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
SecureStore.saveSession(getContext(), json);
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void readSession(PluginCall call) {
|
||||
String json = SecureStore.readSession(getContext());
|
||||
JSObject result = new JSObject();
|
||||
result.put("json", json == null ? JSObject.NULL : json);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void clearSession(PluginCall call) {
|
||||
SecureStore.clearSession(getContext());
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
// ---------- 蓝牙打印 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void listPrinters(PluginCall call) {
|
||||
if (!hasBluetoothPermission()) {
|
||||
requestPermissionForAlias("bluetooth", call, "listPrintersWithPermission");
|
||||
return;
|
||||
}
|
||||
BtPrinterHelper.list(getContext(), call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void listPrintersWithPermission(PluginCall call) {
|
||||
if (!hasBluetoothPermission()) {
|
||||
call.reject("未授予蓝牙权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
BtPrinterHelper.list(getContext(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void printRaw(PluginCall call) {
|
||||
if (!hasBluetoothPermission()) {
|
||||
requestPermissionForAlias("bluetooth", call, "printRawWithPermission");
|
||||
return;
|
||||
}
|
||||
BtPrinterHelper.printRaw(getContext(), call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void printRawWithPermission(PluginCall call) {
|
||||
if (!hasBluetoothPermission()) {
|
||||
call.reject("未授予蓝牙权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
BtPrinterHelper.printRaw(getContext(), call);
|
||||
}
|
||||
|
||||
/**
|
||||
* BLUETOOTH_CONNECT / BLUETOOTH_SCAN 是 Android 12 才引入的运行时权限。
|
||||
* 低版本直接视为已授予,否则 getPermissionState 会永远返回 DENIED,蓝牙打印彻底不可用。
|
||||
*/
|
||||
private boolean hasBluetoothPermission() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
|
||||
return true;
|
||||
}
|
||||
return getPermissionState("bluetooth") == PermissionState.GRANTED;
|
||||
}
|
||||
|
||||
// ---------- 系统日历 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void calendarAvailable(PluginCall call) {
|
||||
CalendarHelper.available(getContext(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void addCalendarEvent(PluginCall call) {
|
||||
// intent 模式不需要任何权限,直接拉起系统日历新建页
|
||||
if ("intent".equals(call.getString("mode", "auto"))) {
|
||||
CalendarHelper.add(getActivity(), call);
|
||||
return;
|
||||
}
|
||||
if (getPermissionState("calendar") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("calendar", call, "addCalendarWithPermission");
|
||||
return;
|
||||
}
|
||||
CalendarHelper.add(getActivity(), call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void addCalendarWithPermission(PluginCall call) {
|
||||
// auto 模式即使被拒绝也继续走,由 CalendarHelper 内部降级到 Intent 通道
|
||||
if (getPermissionState("calendar") != PermissionState.GRANTED
|
||||
&& !"auto".equals(call.getString("mode", "auto"))) {
|
||||
call.reject("未授予日历权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
CalendarHelper.add(getActivity(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void removeCalendarEvent(PluginCall call) {
|
||||
if (getPermissionState("calendar") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("calendar", call, "removeCalendarWithPermission");
|
||||
return;
|
||||
}
|
||||
CalendarHelper.remove(getContext(), call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void removeCalendarWithPermission(PluginCall call) {
|
||||
if (getPermissionState("calendar") != PermissionState.GRANTED) {
|
||||
call.reject("未授予日历权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
CalendarHelper.remove(getContext(), call);
|
||||
}
|
||||
|
||||
// ---------- SAF ----------
|
||||
|
||||
@PluginMethod
|
||||
public void pickFile(PluginCall call) {
|
||||
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType("*/*");
|
||||
JSArray mimeTypes = call.getArray("mimeTypes");
|
||||
if (mimeTypes != null && mimeTypes.length() != 0) {
|
||||
List<String> types = toStringList(mimeTypes);
|
||||
intent.putExtra(Intent.EXTRA_MIME_TYPES, types.toArray(new String[0]));
|
||||
if (types.size() == 1) {
|
||||
intent.setType(types.get(0));
|
||||
}
|
||||
}
|
||||
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, Boolean.TRUE.equals(call.getBoolean("multiple", false)));
|
||||
startActivityForResult(call, intent, "pickFileResult");
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
private void pickFileResult(PluginCall call, ActivityResult result) {
|
||||
if (call == null) {
|
||||
return;
|
||||
}
|
||||
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
|
||||
call.reject("已取消选择", "cancelled");
|
||||
return;
|
||||
}
|
||||
Intent data = result.getData();
|
||||
List<Uri> uris = new ArrayList<>();
|
||||
if (data != null) {
|
||||
ClipData clipData = data.getClipData();
|
||||
if (clipData != null) {
|
||||
for (int index = 0; index < clipData.getItemCount(); index++) {
|
||||
Uri uri = clipData.getItemAt(index).getUri();
|
||||
if (uri != null) {
|
||||
uris.add(uri);
|
||||
}
|
||||
}
|
||||
} else if (data.getData() != null) {
|
||||
uris.add(data.getData());
|
||||
}
|
||||
}
|
||||
if (uris.isEmpty()) {
|
||||
call.reject("没有选中文件", "cancelled");
|
||||
return;
|
||||
}
|
||||
SafHelper.copyToCache(getContext(), call, uris);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void saveFile(PluginCall call) {
|
||||
String fileName = call.getString("fileName");
|
||||
String data = call.getString("data");
|
||||
if (fileName == null || fileName.isEmpty() || data == null) {
|
||||
call.reject("缺少文件名或内容", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
|
||||
intent.addCategory(Intent.CATEGORY_OPENABLE);
|
||||
intent.setType(call.getString("mimeType", "application/octet-stream"));
|
||||
intent.putExtra(Intent.EXTRA_TITLE, fileName);
|
||||
startActivityForResult(call, intent, "saveFileResult");
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
private void saveFileResult(PluginCall call, ActivityResult result) {
|
||||
if (call == null) {
|
||||
return;
|
||||
}
|
||||
if (result.getResultCode() != android.app.Activity.RESULT_OK) {
|
||||
call.reject("已取消保存", "cancelled");
|
||||
return;
|
||||
}
|
||||
Intent data = result.getData();
|
||||
Uri uri = data == null ? null : data.getData();
|
||||
if (uri == null) {
|
||||
call.reject("没有选择保存位置", "cancelled");
|
||||
return;
|
||||
}
|
||||
SafHelper.writeToUri(getContext(), call, uri);
|
||||
}
|
||||
|
||||
// ---------- 前台状态与网络 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void getAppState(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("isActive", systemHelper.isActive());
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void getNetworkStatus(PluginCall call) {
|
||||
systemHelper.getNetworkStatus(call);
|
||||
}
|
||||
|
||||
// ---------- 权限状态与设置跳转 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void getPermissionStates(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("camera", getPermissionState("camera").toString());
|
||||
result.put("microphone", getPermissionState("microphone").toString());
|
||||
result.put("calendar", getPermissionState("calendar").toString());
|
||||
result.put("contacts", getPermissionState("contacts").toString());
|
||||
// 蓝牙在 Android 12 以下没有运行时权限,直接算已授予
|
||||
result.put(
|
||||
"bluetooth",
|
||||
hasBluetoothPermission() ? "granted" : getPermissionState("bluetooth").toString()
|
||||
);
|
||||
// 通知在 Android 13 以下没有运行时权限,用系统开关状态代替
|
||||
result.put(
|
||||
"notifications",
|
||||
NotificationScheduler.hasNotificationPermission(getContext()) ? "granted" : "denied"
|
||||
);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void openAppSettings(PluginCall call) {
|
||||
systemHelper.openAppSettings(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void openNotificationSettings(PluginCall call) {
|
||||
systemHelper.openNotificationSettings(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void openBatteryOptimizationSettings(PluginCall call) {
|
||||
systemHelper.openBatteryOptimizationSettings(call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void isIgnoringBatteryOptimizations(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("ignoring", systemHelper.isIgnoringBatteryOptimizations());
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---------- 设备控制 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void getDeviceId(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("androidId", systemHelper.getAndroidId());
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void getRingerMode(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("mode", systemHelper.getRingerMode());
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void setKeepAwake(PluginCall call) {
|
||||
if (!ensureActivity(call)) {
|
||||
return;
|
||||
}
|
||||
boolean enabled = Boolean.TRUE.equals(call.getBoolean("enabled", true));
|
||||
getActivity().runOnUiThread(() -> {
|
||||
systemHelper.setKeepAwake(getActivity(), enabled);
|
||||
JSObject result = new JSObject();
|
||||
result.put("enabled", enabled);
|
||||
call.resolve(result);
|
||||
});
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void setOrientation(PluginCall call) {
|
||||
if (!ensureActivity(call)) {
|
||||
return;
|
||||
}
|
||||
String orientation = call.getString("orientation", "auto");
|
||||
getActivity().runOnUiThread(() -> {
|
||||
systemHelper.setOrientation(getActivity(), orientation);
|
||||
JSObject result = new JSObject();
|
||||
result.put("orientation", orientation);
|
||||
call.resolve(result);
|
||||
});
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void restartApp(PluginCall call) {
|
||||
if (!ensureActivity(call)) {
|
||||
return;
|
||||
}
|
||||
// 先 resolve,重建后这个 PluginCall 就没地方回了
|
||||
call.resolve();
|
||||
getActivity().runOnUiThread(() -> systemHelper.restartApp(getActivity()));
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void clearWebCache(PluginCall call) {
|
||||
if (!ensureActivity(call)) {
|
||||
return;
|
||||
}
|
||||
boolean storage = Boolean.TRUE.equals(call.getBoolean("storage", false));
|
||||
android.webkit.WebView webView = getBridge() == null ? null : getBridge().getWebView();
|
||||
getActivity().runOnUiThread(() -> {
|
||||
systemHelper.clearWebCache(webView, storage);
|
||||
call.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
private boolean ensureActivity(PluginCall call) {
|
||||
if (getActivity() == null) {
|
||||
call.reject("页面已销毁,无法执行", "no_activity");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------- 通讯录 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void contactsAvailable(PluginCall call) {
|
||||
ContactsHelper.available(getContext(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void addContact(PluginCall call) {
|
||||
if (getPermissionState("contacts") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("contacts", call, "addContactWithPermission");
|
||||
return;
|
||||
}
|
||||
ContactsHelper.add(getContext(), call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void addContactWithPermission(PluginCall call) {
|
||||
if (getPermissionState("contacts") != PermissionState.GRANTED) {
|
||||
call.reject("未授予通讯录权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
ContactsHelper.add(getContext(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void syncContacts(PluginCall call) {
|
||||
if (getPermissionState("contacts") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("contacts", call, "syncContactsWithPermission");
|
||||
return;
|
||||
}
|
||||
ContactsHelper.sync(getContext(), call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void syncContactsWithPermission(PluginCall call) {
|
||||
if (getPermissionState("contacts") != PermissionState.GRANTED) {
|
||||
call.reject("未授予通讯录权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
ContactsHelper.sync(getContext(), call);
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void clearContacts(PluginCall call) {
|
||||
if (getPermissionState("contacts") != PermissionState.GRANTED) {
|
||||
requestPermissionForAlias("contacts", call, "clearContactsWithPermission");
|
||||
return;
|
||||
}
|
||||
ContactsHelper.clear(getContext(), call);
|
||||
}
|
||||
|
||||
@PermissionCallback
|
||||
private void clearContactsWithPermission(PluginCall call) {
|
||||
if (getPermissionState("contacts") != PermissionState.GRANTED) {
|
||||
call.reject("未授予通讯录权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
ContactsHelper.clear(getContext(), call);
|
||||
}
|
||||
|
||||
// ---------- 杂项 ----------
|
||||
|
||||
@PluginMethod
|
||||
public void vibrate(PluginCall call) {
|
||||
int duration = toInt(call.getInt("ms"), 30);
|
||||
Vibrator vibrator;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
VibratorManager manager = (VibratorManager) getContext().getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
|
||||
vibrator = manager == null ? null : manager.getDefaultVibrator();
|
||||
} else {
|
||||
vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
|
||||
}
|
||||
if (vibrator != null && vibrator.hasVibrator()) {
|
||||
vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
|
||||
}
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void copy(PluginCall call) {
|
||||
String text = call.getString("text");
|
||||
if (text == null) {
|
||||
call.reject("缺少文本", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
ClipboardManager manager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
if (manager == null) {
|
||||
call.reject("剪贴板不可用", "service_unavailable");
|
||||
return;
|
||||
}
|
||||
manager.setPrimaryClip(ClipData.newPlainText("NativeKit", text));
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
public void getDeviceInfo(PluginCall call) {
|
||||
JSObject result = new JSObject();
|
||||
result.put("brand", Build.BRAND);
|
||||
result.put("model", Build.MODEL);
|
||||
result.put("manufacturer", Build.MANUFACTURER);
|
||||
result.put("sdkInt", Build.VERSION.SDK_INT);
|
||||
result.put("webViewVersion", resolveWebViewVersion(getContext()));
|
||||
result.put("packageName", getContext().getPackageName());
|
||||
JSObject info = buildInfo(getContext());
|
||||
result.put("versionCode", info.optLong("versionCode"));
|
||||
result.put("versionName", info.optString("versionName"));
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
// ---------- 内部工具 ----------
|
||||
|
||||
private static String safeString(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private static int toInt(Integer value, int fallback) {
|
||||
return value == null ? fallback : value;
|
||||
}
|
||||
|
||||
private static List<String> toStringList(JSArray array) {
|
||||
List<String> result = new ArrayList<>();
|
||||
for (int index = 0; index < array.length(); index++) {
|
||||
Object item = array.opt(index);
|
||||
if (item != null) {
|
||||
result.add(String.valueOf(item));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String resolveWebViewVersion(Context context) {
|
||||
try {
|
||||
String userAgent = WebSettings.getDefaultUserAgent(context);
|
||||
java.util.regex.Matcher matcher = java.util.regex.Pattern
|
||||
.compile("Chrome/([\\d.]+)")
|
||||
.matcher(userAgent);
|
||||
return matcher.find() ? matcher.group(1) : userAgent;
|
||||
} catch (Exception error) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
/**
|
||||
* 定时通知的触发入口。
|
||||
*
|
||||
* <p>只做转发:真正的发通知与重排逻辑在 {@link NotificationScheduler#handleFire}。
|
||||
*/
|
||||
public class NotificationAlarmReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (intent == null) {
|
||||
return;
|
||||
}
|
||||
int id = intent.getIntExtra(NotificationScheduler.EXTRA_ID, -1);
|
||||
if (id < 0) {
|
||||
return;
|
||||
}
|
||||
NotificationScheduler.handleFire(context, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
|
||||
import androidx.core.app.NotificationCompat;
|
||||
import androidx.core.app.NotificationManagerCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
import com.getcapacitor.JSArray;
|
||||
import com.getcapacitor.JSObject;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.imyeyu.gao.customer.MainActivity;
|
||||
import com.imyeyu.gao.customer.R;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 本地通知的调度与恢复。
|
||||
*
|
||||
* <p>不用 {@code setRepeating}:它在 Doze 下会被打成批量窗口,误差可达几十分钟。
|
||||
* 这里用一次性精确闹钟,触发后自行计算下一次并重排,配合 BOOT_COMPLETED 恢复,
|
||||
* 设备重启、应用覆盖安装都不会丢任务。
|
||||
*/
|
||||
public final class NotificationScheduler {
|
||||
|
||||
public static final String EXTRA_ROUTE = "nativekit_route";
|
||||
public static final String EXTRA_ID = "nativekit_notify_id";
|
||||
|
||||
static final String CHANNEL_REMINDER = "nativekit_reminder";
|
||||
static final String CHANNEL_ALERT = "nativekit_alert";
|
||||
|
||||
private static final String PREFS = "nativekit_notifications";
|
||||
private static final String KEY_TASKS = "tasks";
|
||||
private static final String KEY_NEXT_ID = "next_id";
|
||||
private static final int BASE_ID = 1000;
|
||||
private static final Object LOCK = new Object();
|
||||
|
||||
private final Context context;
|
||||
|
||||
NotificationScheduler(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
}
|
||||
|
||||
// ---------- 渠道 ----------
|
||||
|
||||
/** 渠道只需创建一次,重复调用无副作用 */
|
||||
public static void ensureChannels(Context context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
return;
|
||||
}
|
||||
NotificationManager manager = context.getSystemService(NotificationManager.class);
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationChannel reminder = new NotificationChannel(
|
||||
CHANNEL_REMINDER,
|
||||
"业务提醒",
|
||||
NotificationManager.IMPORTANCE_DEFAULT
|
||||
);
|
||||
reminder.setDescription("跟进提醒、生日提醒、履约到期");
|
||||
reminder.enableVibration(true);
|
||||
|
||||
NotificationChannel alert = new NotificationChannel(
|
||||
CHANNEL_ALERT,
|
||||
"业务告警",
|
||||
NotificationManager.IMPORTANCE_HIGH
|
||||
);
|
||||
alert.setDescription("待核销、库存告警等需要立即处理的消息");
|
||||
alert.enableVibration(true);
|
||||
|
||||
manager.createNotificationChannels(java.util.Arrays.asList(reminder, alert));
|
||||
}
|
||||
|
||||
// ---------- 调度 ----------
|
||||
|
||||
void schedule(PluginCall call) {
|
||||
String title = call.getString("title");
|
||||
String body = call.getString("body");
|
||||
Long at = call.getLong("at");
|
||||
if (title == null || title.isEmpty() || body == null || at == null) {
|
||||
call.reject("缺少标题、内容或触发时间", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
if (at <= System.currentTimeMillis()) {
|
||||
call.reject("触发时间必须晚于当前时间", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
Integer requestedId = call.getInt("id");
|
||||
int id;
|
||||
synchronized (LOCK) {
|
||||
id = requestedId == null ? nextId(context) : requestedId;
|
||||
// 同 id 视为覆盖:先撤销旧闹钟与旧通知
|
||||
cancelInternal(id);
|
||||
}
|
||||
|
||||
Task task = new Task();
|
||||
task.id = id;
|
||||
task.title = title;
|
||||
task.body = body;
|
||||
task.at = at;
|
||||
task.repeat = normalizeRepeat(call.getString("repeat"));
|
||||
task.route = cleanText(call.getString("route"));
|
||||
task.owner = cleanText(call.getString("owner"));
|
||||
task.channel = CHANNEL_ALERT.equals(toChannelId(call.getString("channel")))
|
||||
? CHANNEL_ALERT
|
||||
: CHANNEL_REMINDER;
|
||||
|
||||
synchronized (LOCK) {
|
||||
List<Task> tasks = readTasks(context);
|
||||
tasks.removeIf(item -> item.id == task.id);
|
||||
tasks.add(task);
|
||||
writeTasks(context, tasks);
|
||||
scheduleAlarm(context, task);
|
||||
}
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("id", id);
|
||||
result.put("at", at);
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
void cancel(int id) {
|
||||
synchronized (LOCK) {
|
||||
cancelInternal(id);
|
||||
List<Task> tasks = readTasks(context);
|
||||
tasks.removeIf(item -> item.id == id);
|
||||
writeTasks(context, tasks);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空任务。
|
||||
*
|
||||
* @param owner 非空时只清该归属的任务,用于共用设备上的账号切换
|
||||
*/
|
||||
void cancelAll(String owner) {
|
||||
synchronized (LOCK) {
|
||||
List<Task> tasks = readTasks(context);
|
||||
List<Task> remain = new ArrayList<>();
|
||||
for (Task task : tasks) {
|
||||
if (owner == null || owner.isEmpty() || owner.equals(task.owner)) {
|
||||
cancelInternal(task.id);
|
||||
} else {
|
||||
remain.add(task);
|
||||
}
|
||||
}
|
||||
writeTasks(context, remain);
|
||||
}
|
||||
}
|
||||
|
||||
/** 列出已排程的任务,按触发时间升序;owner 非空时只返回该归属的 */
|
||||
void list(PluginCall call) {
|
||||
String owner = call.getString("owner");
|
||||
synchronized (LOCK) {
|
||||
List<Task> tasks = readTasks(context);
|
||||
tasks.sort(Comparator.comparingLong(task -> task.at));
|
||||
|
||||
JSArray items = new JSArray();
|
||||
for (Task task : tasks) {
|
||||
if (owner != null && !owner.isEmpty() && !owner.equals(task.owner)) {
|
||||
continue;
|
||||
}
|
||||
JSObject item = new JSObject();
|
||||
item.put("id", task.id);
|
||||
item.put("title", task.title);
|
||||
item.put("body", task.body);
|
||||
item.put("at", task.at);
|
||||
item.put("repeat", task.repeat);
|
||||
item.put("route", task.route == null ? JSObject.NULL : task.route);
|
||||
item.put("owner", task.owner == null ? JSObject.NULL : task.owner);
|
||||
item.put("channel", CHANNEL_ALERT.equals(task.channel) ? "alert" : "reminder");
|
||||
items.put(item);
|
||||
}
|
||||
|
||||
JSObject result = new JSObject();
|
||||
result.put("items", items);
|
||||
call.resolve(result);
|
||||
}
|
||||
}
|
||||
|
||||
/** 重启或覆盖安装后恢复未过期任务,过期的重复任务顺延到下一次 */
|
||||
public static void restore(Context context) {
|
||||
synchronized (LOCK) {
|
||||
List<Task> tasks = readTasks(context);
|
||||
List<Task> alive = new ArrayList<>();
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
for (Task task : tasks) {
|
||||
if (task.at <= now) {
|
||||
if ("none".equals(task.repeat)) {
|
||||
continue;
|
||||
}
|
||||
task.at = nextOccurrence(task.at, task.repeat, now);
|
||||
}
|
||||
alive.add(task);
|
||||
scheduleAlarm(context, task);
|
||||
}
|
||||
writeTasks(context, alive);
|
||||
}
|
||||
}
|
||||
|
||||
/** 闹钟触发:发通知,重复任务顺延 */
|
||||
public static void handleFire(Context context, int id) {
|
||||
synchronized (LOCK) {
|
||||
List<Task> tasks = readTasks(context);
|
||||
Task target = null;
|
||||
for (Task task : tasks) {
|
||||
if (task.id == id) {
|
||||
target = task;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (target == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
post(context, target);
|
||||
|
||||
if ("none".equals(target.repeat)) {
|
||||
tasks.removeIf(item -> item.id == id);
|
||||
writeTasks(context, tasks);
|
||||
return;
|
||||
}
|
||||
|
||||
target.at = nextOccurrence(target.at, target.repeat, System.currentTimeMillis());
|
||||
writeTasks(context, tasks);
|
||||
scheduleAlarm(context, target);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 权限 ----------
|
||||
|
||||
static boolean hasNotificationPermission(Context context) {
|
||||
if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) {
|
||||
return false;
|
||||
}
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
return true;
|
||||
}
|
||||
return ContextCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS)
|
||||
== PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
static boolean canScheduleExactAlarms(Context context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
|
||||
return true;
|
||||
}
|
||||
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
return manager != null && manager.canScheduleExactAlarms();
|
||||
}
|
||||
|
||||
// ---------- 内部实现 ----------
|
||||
|
||||
private static void scheduleAlarm(Context context, Task task) {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Intent intent = new Intent(context, NotificationAlarmReceiver.class);
|
||||
// data 参与 PendingIntent 去重,避免同 requestCode 的旧闹钟被覆盖
|
||||
intent.setData(Uri.parse("nativekit://notify/" + task.id));
|
||||
intent.putExtra(EXTRA_ID, task.id);
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
|
||||
PendingIntent pending = PendingIntent.getBroadcast(context, task.id, intent, flags);
|
||||
|
||||
try {
|
||||
if (canScheduleExactAlarms(context)) {
|
||||
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, task.at, pending);
|
||||
} else {
|
||||
// 未授权精确闹钟时降级,误差可接受,但不能直接失败
|
||||
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, task.at, pending);
|
||||
}
|
||||
} catch (SecurityException error) {
|
||||
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, task.at, pending);
|
||||
}
|
||||
}
|
||||
|
||||
private static void post(Context context, Task task) {
|
||||
if (!hasNotificationPermission(context)) {
|
||||
// 没权限也必须让重复任务继续走下去,否则一次拒绝就永久失效
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, task.channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(task.title)
|
||||
.setContentText(task.body)
|
||||
.setStyle(new NotificationCompat.BigTextStyle().bigText(task.body))
|
||||
.setAutoCancel(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
||||
.setPriority(
|
||||
CHANNEL_ALERT.equals(task.channel)
|
||||
? NotificationCompat.PRIORITY_HIGH
|
||||
: NotificationCompat.PRIORITY_DEFAULT
|
||||
);
|
||||
|
||||
if (task.route != null && !task.route.isEmpty()) {
|
||||
Intent intent = new Intent(context, MainActivity.class);
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
||||
intent.putExtra(EXTRA_ROUTE, task.route);
|
||||
PendingIntent contentIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
task.id,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
||||
);
|
||||
builder.setContentIntent(contentIntent);
|
||||
}
|
||||
|
||||
Notification notification = builder.build();
|
||||
NotificationManagerCompat.from(context).notify(task.id, notification);
|
||||
}
|
||||
|
||||
private void cancelInternal(int id) {
|
||||
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
if (manager != null) {
|
||||
Intent intent = new Intent(context, NotificationAlarmReceiver.class);
|
||||
intent.setData(Uri.parse("nativekit://notify/" + id));
|
||||
PendingIntent pending = PendingIntent.getBroadcast(
|
||||
context,
|
||||
id,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
|
||||
);
|
||||
manager.cancel(pending);
|
||||
}
|
||||
NotificationManagerCompat.from(context).cancel(id);
|
||||
}
|
||||
|
||||
/** 空串与字符串 "null" 都归一成 null,避免脏值被当成真实路由 */
|
||||
private static String cleanText(String value) {
|
||||
if (value == null || value.isEmpty() || "null".equals(value)) {
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String normalizeRepeat(String repeat) { if ("daily".equals(repeat) || "weekly".equals(repeat) || "yearly".equals(repeat)) {
|
||||
return repeat;
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
|
||||
private static String toChannelId(String channel) {
|
||||
return "alert".equals(channel) ? CHANNEL_ALERT : CHANNEL_REMINDER;
|
||||
}
|
||||
|
||||
/** 从 at 起找到第一个晚于 now 的时刻,按本地时区计算 */
|
||||
private static long nextOccurrence(long at, String repeat, long now) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTimeInMillis(at);
|
||||
|
||||
if ("yearly".equals(repeat)) {
|
||||
do {
|
||||
calendar.add(Calendar.YEAR, 1);
|
||||
} while (calendar.getTimeInMillis() <= now);
|
||||
return calendar.getTimeInMillis();
|
||||
}
|
||||
|
||||
int step = "weekly".equals(repeat) ? 7 : 1;
|
||||
do {
|
||||
calendar.add(Calendar.DAY_OF_MONTH, step);
|
||||
} while (calendar.getTimeInMillis() <= now);
|
||||
return calendar.getTimeInMillis();
|
||||
}
|
||||
|
||||
private static int nextId(Context context) {
|
||||
SharedPreferences preferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
int id = preferences.getInt(KEY_NEXT_ID, BASE_ID);
|
||||
preferences.edit().putInt(KEY_NEXT_ID, id + 1).apply();
|
||||
return id;
|
||||
}
|
||||
|
||||
private static List<Task> readTasks(Context context) {
|
||||
SharedPreferences preferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
|
||||
String raw = preferences.getString(KEY_TASKS, null);
|
||||
List<Task> tasks = new ArrayList<>();
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return tasks;
|
||||
}
|
||||
|
||||
try {
|
||||
JSONArray array = new JSONArray(raw);
|
||||
for (int index = 0; index < array.length(); index++) {
|
||||
JSONObject object = array.optJSONObject(index);
|
||||
if (object == null) {
|
||||
continue;
|
||||
}
|
||||
Task task = new Task();
|
||||
task.id = object.optInt("id");
|
||||
task.title = object.optString("title");
|
||||
task.body = object.optString("body");
|
||||
task.at = object.optLong("at");
|
||||
task.repeat = normalizeRepeat(object.optString("repeat"));
|
||||
// optString 遇到 JSON null 会返回字符串 "null";早期版本还会把它原样写回存储,
|
||||
// 所以这里两种形态都当没有处理,避免通知点击跳到 "/null"
|
||||
task.route = cleanText(object.isNull("route") ? null : object.optString("route", null));
|
||||
task.owner = cleanText(object.isNull("owner") ? null : object.optString("owner", null));
|
||||
task.channel = toChannelId(object.optString("channel"));
|
||||
if (0 < task.id && 0 < task.at) {
|
||||
tasks.add(task);
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 内容损坏时按空列表处理,避免整个提醒体系卡死
|
||||
}
|
||||
return tasks;
|
||||
}
|
||||
|
||||
private static void writeTasks(Context context, List<Task> tasks) {
|
||||
JSONArray array = new JSONArray();
|
||||
for (Task task : tasks) {
|
||||
JSONObject object = new JSONObject();
|
||||
try {
|
||||
object.put("id", task.id);
|
||||
object.put("title", task.title);
|
||||
object.put("body", task.body);
|
||||
object.put("at", task.at);
|
||||
object.put("repeat", task.repeat);
|
||||
object.put("route", task.route == null ? JSONObject.NULL : task.route);
|
||||
object.put("owner", task.owner == null ? JSONObject.NULL : task.owner);
|
||||
object.put("channel", CHANNEL_ALERT.equals(task.channel) ? "alert" : "reminder");
|
||||
array.put(object);
|
||||
} catch (Exception ignored) {
|
||||
// 单条序列化失败不影响其余任务
|
||||
}
|
||||
}
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.putString(KEY_TASKS, array.toString())
|
||||
.apply();
|
||||
}
|
||||
|
||||
/** 任务模型,字段与前端 options 一一对应 */
|
||||
static final class Task {
|
||||
int id;
|
||||
String title;
|
||||
String body;
|
||||
long at;
|
||||
String repeat;
|
||||
String route;
|
||||
/** 归属标识,通常是登录用户 ID,用于共用设备上的隔离 */
|
||||
String owner;
|
||||
String channel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.pdf.PdfDocument;
|
||||
import android.os.Bundle;
|
||||
import android.os.CancellationSignal;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.print.PageRange;
|
||||
import android.print.PrintAttributes;
|
||||
import android.print.PrintDocumentAdapter;
|
||||
import android.print.PrintDocumentInfo;
|
||||
import android.print.PrintManager;
|
||||
import android.print.pdf.PrintedPdfDocument;
|
||||
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 系统打印。
|
||||
*
|
||||
* <p>替代 Web 侧的 {@code window.open} 打印:那个做法在 Capacitor 里会把整页外抛到浏览器,
|
||||
* 回来之后 App 状态全丢。
|
||||
*
|
||||
* <p>系统打印框架无法静默打印,一定会弹面板 —— 这是 Android 的限制,要静默只能走
|
||||
* IPP/CUPS 直连或厂商 SDK。
|
||||
*/
|
||||
final class PrintHelper {
|
||||
|
||||
private PrintHelper() {
|
||||
}
|
||||
|
||||
static void print(Activity activity, PluginCall call, List<String> paths, String jobName) {
|
||||
if (paths.isEmpty()) {
|
||||
call.reject("没有待打印文件", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
File first = new File(MediaInfo.stripScheme(paths.get(0)));
|
||||
if (!first.isFile()) {
|
||||
call.reject("文件不存在:" + paths.get(0), "file_not_found");
|
||||
return;
|
||||
}
|
||||
|
||||
PrintManager manager = (PrintManager) activity.getSystemService(Context.PRINT_SERVICE);
|
||||
if (manager == null) {
|
||||
call.reject("打印服务不可用", "service_unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
PrintAttributes attributes = new PrintAttributes.Builder()
|
||||
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
|
||||
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
|
||||
.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
|
||||
.build();
|
||||
|
||||
String safeJobName = jobName == null || jobName.isEmpty() ? "GaoCustomer" : jobName;
|
||||
manager.print(safeJobName, new FilesPrintAdapter(activity, paths), attributes);
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* 单文件 PDF 直接流式拷贝;图片则逐页绘制到同一个 PDF。
|
||||
*
|
||||
* <p>二维码批量打印是主路径:一页一张 2480×3508 的 PNG,必须先按页面尺寸采样解码,
|
||||
* 否则一次解码多张直接 OOM。
|
||||
*/
|
||||
private static final class FilesPrintAdapter extends PrintDocumentAdapter {
|
||||
|
||||
private final Context context;
|
||||
private final List<String> paths;
|
||||
private PrintAttributes attributes;
|
||||
private int pageCount;
|
||||
|
||||
FilesPrintAdapter(Context context, List<String> paths) {
|
||||
this.context = context;
|
||||
this.paths = paths;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLayout(
|
||||
PrintAttributes oldAttributes,
|
||||
PrintAttributes newAttributes,
|
||||
CancellationSignal cancellationSignal,
|
||||
LayoutResultCallback callback,
|
||||
Bundle extras
|
||||
) {
|
||||
attributes = newAttributes;
|
||||
boolean pdf = paths.size() == 1 && isPdf(paths.get(0));
|
||||
pageCount = pdf ? 1 : paths.size();
|
||||
|
||||
PrintDocumentInfo info = new PrintDocumentInfo.Builder("gao-customer-print")
|
||||
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
|
||||
.setPageCount(pageCount)
|
||||
.build();
|
||||
|
||||
if (isCancelled(cancellationSignal)) {
|
||||
callback.onLayoutCancelled();
|
||||
return;
|
||||
}
|
||||
callback.onLayoutFinished(info, !newAttributes.equals(oldAttributes));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWrite(
|
||||
PageRange[] pages,
|
||||
ParcelFileDescriptor destination,
|
||||
CancellationSignal cancellationSignal,
|
||||
WriteResultCallback callback
|
||||
) {
|
||||
try {
|
||||
if (paths.size() == 1 && isPdf(paths.get(0))) {
|
||||
copyFile(new File(MediaInfo.stripScheme(paths.get(0))), destination);
|
||||
} else {
|
||||
writeImages(destination, cancellationSignal);
|
||||
}
|
||||
callback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES });
|
||||
} catch (Exception error) {
|
||||
callback.onWriteFailed(error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void writeImages(ParcelFileDescriptor destination, CancellationSignal cancellationSignal)
|
||||
throws Exception {
|
||||
PrintedPdfDocument document = new PrintedPdfDocument(context, attributes);
|
||||
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
paint.setFilterBitmap(true);
|
||||
|
||||
try {
|
||||
int pageNumber = 1;
|
||||
for (String path : paths) {
|
||||
if (isCancelled(cancellationSignal)) {
|
||||
return;
|
||||
}
|
||||
File file = new File(MediaInfo.stripScheme(path));
|
||||
Bitmap bitmap = decode(file);
|
||||
if (bitmap == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
|
||||
document.getPageWidth(),
|
||||
document.getPageHeight(),
|
||||
pageNumber
|
||||
).create();
|
||||
PdfDocument.Page page = document.startPage(pageInfo);
|
||||
Canvas canvas = page.getCanvas();
|
||||
canvas.drawColor(Color.WHITE);
|
||||
|
||||
RectF target = fitCenter(bitmap, document.getPageWidth(), document.getPageHeight());
|
||||
canvas.drawBitmap(bitmap, null, target, paint);
|
||||
document.finishPage(page);
|
||||
bitmap.recycle();
|
||||
pageNumber++;
|
||||
}
|
||||
|
||||
if (1 < pageNumber) {
|
||||
try (OutputStream output = new FileOutputStream(destination.getFileDescriptor())) {
|
||||
document.writeTo(output);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
document.close();
|
||||
}
|
||||
}
|
||||
|
||||
private static RectF fitCenter(Bitmap bitmap, int width, int height) {
|
||||
float scale = Math.min(
|
||||
(float) width / bitmap.getWidth(),
|
||||
(float) height / bitmap.getHeight()
|
||||
);
|
||||
float drawWidth = bitmap.getWidth() * scale;
|
||||
float drawHeight = bitmap.getHeight() * scale;
|
||||
float left = (width - drawWidth) / 2f;
|
||||
float top = (height - drawHeight) / 2f;
|
||||
return new RectF(left, top, left + drawWidth, top + drawHeight);
|
||||
}
|
||||
|
||||
/** 按页面最长边采样,避免一张 A4 大图直接吃掉几百 MB */
|
||||
private static Bitmap decode(File file) {
|
||||
BitmapFactory.Options bounds = new BitmapFactory.Options();
|
||||
bounds.inJustDecodeBounds = true;
|
||||
BitmapFactory.decodeFile(file.getAbsolutePath(), bounds);
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int longest = Math.max(bounds.outWidth, bounds.outHeight);
|
||||
int sample = 1;
|
||||
while (2480 < longest / sample) {
|
||||
sample *= 2;
|
||||
}
|
||||
|
||||
BitmapFactory.Options options = new BitmapFactory.Options();
|
||||
options.inSampleSize = sample;
|
||||
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
|
||||
return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
|
||||
}
|
||||
|
||||
private static void copyFile(File file, ParcelFileDescriptor destination) throws Exception {
|
||||
try (InputStream input = new FileInputStream(file);
|
||||
OutputStream output = new FileOutputStream(destination.getFileDescriptor())) {
|
||||
byte[] buffer = new byte[32768];
|
||||
int read;
|
||||
while ((read = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, read);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPdf(String path) {
|
||||
return MediaInfo.stripScheme(path).toLowerCase(Locale.ROOT).endsWith(".pdf");
|
||||
}
|
||||
|
||||
private static boolean isCancelled(CancellationSignal signal) {
|
||||
return signal != null && signal.isCanceled();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.provider.OpenableColumns;
|
||||
import android.util.Base64;
|
||||
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* SAF 文件选择与另存。
|
||||
*
|
||||
* <p>选中的 {@code content://} 在 WebView 的 fetch 里读不到,必须先拷到 cache 再以
|
||||
* {@code file://} 交给前端。这一步不能省,否则接口看着通、实际用不了。
|
||||
*/
|
||||
final class SafHelper {
|
||||
|
||||
private static final String CACHE_DIR = "nativekit-pick";
|
||||
private static final String UNSAFE = "[^\\w.\\-\\u4e00-\\u9fa5]";
|
||||
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
|
||||
|
||||
private SafHelper() {
|
||||
}
|
||||
|
||||
/** 把选中的 URI 复制到 cache,异步回调 */
|
||||
static void copyToCache(Context context, PluginCall call, List<Uri> uris) {
|
||||
EXECUTOR.execute(() -> {
|
||||
File directory = new File(context.getCacheDir(), CACHE_DIR);
|
||||
if (!directory.exists() && !directory.mkdirs()) {
|
||||
call.reject("无法创建缓存目录", "io_error");
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> paths = new ArrayList<>();
|
||||
for (Uri uri : uris) {
|
||||
String name = sanitize(queryName(context, uri));
|
||||
File target = new File(directory, System.currentTimeMillis() + "-" + name);
|
||||
try (InputStream input = context.getContentResolver().openInputStream(uri);
|
||||
OutputStream output = new FileOutputStream(target)) {
|
||||
if (input == null) {
|
||||
continue;
|
||||
}
|
||||
byte[] buffer = new byte[32768];
|
||||
int read;
|
||||
while ((read = input.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, read);
|
||||
}
|
||||
paths.add(target.getAbsolutePath());
|
||||
} catch (Exception error) {
|
||||
target.delete();
|
||||
}
|
||||
}
|
||||
|
||||
if (paths.isEmpty()) {
|
||||
call.reject("读取文件失败", "io_error");
|
||||
return;
|
||||
}
|
||||
call.resolve(MediaInfo.buildFiles(context, paths));
|
||||
});
|
||||
}
|
||||
|
||||
/** 把 base64 内容写进用户选定的 URI */
|
||||
static void writeToUri(Context context, PluginCall call, Uri uri) {
|
||||
String data = call.getString("data");
|
||||
if (data == null) {
|
||||
call.reject("缺少文件内容", "invalid_argument");
|
||||
return;
|
||||
}
|
||||
|
||||
EXECUTOR.execute(() -> {
|
||||
try (OutputStream output = context.getContentResolver().openOutputStream(uri)) {
|
||||
if (output == null) {
|
||||
call.reject("无法写入所选位置", "io_error");
|
||||
return;
|
||||
}
|
||||
output.write(Base64.decode(data, Base64.DEFAULT));
|
||||
output.flush();
|
||||
} catch (Exception error) {
|
||||
call.reject("保存失败:" + error.getMessage(), "io_error");
|
||||
return;
|
||||
}
|
||||
|
||||
com.getcapacitor.JSObject result = new com.getcapacitor.JSObject();
|
||||
result.put("path", uri.toString());
|
||||
result.put("name", queryName(context, uri));
|
||||
call.resolve(result);
|
||||
});
|
||||
}
|
||||
|
||||
private static String queryName(Context context, Uri uri) {
|
||||
try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
|
||||
if (cursor != null && cursor.moveToFirst()) {
|
||||
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
|
||||
if (0 <= index) {
|
||||
String name = cursor.getString(index);
|
||||
if (name != null && !name.isEmpty()) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 查询失败时退回路径末段
|
||||
}
|
||||
String fallback = uri.getLastPathSegment();
|
||||
return fallback == null || fallback.isEmpty() ? "file" : fallback;
|
||||
}
|
||||
|
||||
private static String sanitize(String name) {
|
||||
String cleaned = name.replaceAll(UNSAFE, "_");
|
||||
if (120 < cleaned.length()) {
|
||||
cleaned = cleaned.substring(cleaned.length() - 120);
|
||||
}
|
||||
return cleaned.isEmpty() ? "file" : cleaned;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.security.keystore.KeyGenParameterSpec;
|
||||
import android.security.keystore.KeyProperties;
|
||||
import android.util.Base64;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyStore;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
|
||||
/**
|
||||
* 登录态的加密存储。
|
||||
*
|
||||
* <p>密钥由 Android Keystore 生成并保存在 TEE,无法导出;密文落在独立的 SharedPreferences。
|
||||
* 不使用 androidx.security:security-crypto —— 它在部分机型上创建 MasterKey 失败,且长期停留在 alpha。
|
||||
*
|
||||
* <p>存储格式为 Base64(IV[12] + 密文 + GCM tag),密钥被系统清除(恢复出厂、锁屏密码重置)时
|
||||
* 解密会失败,此时按「无会话」处理,让用户重新登录,不抛异常。
|
||||
*/
|
||||
public final class SecureStore {
|
||||
|
||||
private static final String KEY_STORE = "AndroidKeyStore";
|
||||
private static final String KEY_ALIAS = "nativekit_session_key";
|
||||
private static final String PREFS_NAME = "nativekit_secure";
|
||||
private static final String FIELD_SESSION = "session";
|
||||
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
|
||||
private static final int IV_BYTES = 12;
|
||||
private static final int TAG_BITS = 128;
|
||||
private static final int KEY_BITS = 256;
|
||||
|
||||
private SecureStore() {
|
||||
}
|
||||
|
||||
/** 写入加密会话;传空字符串等价于清除 */
|
||||
public static void saveSession(Context context, String json) {
|
||||
if (json == null || json.isEmpty()) {
|
||||
clearSession(context);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey());
|
||||
byte[] encrypted = cipher.doFinal(json.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] iv = cipher.getIV();
|
||||
byte[] payload = new byte[iv.length + encrypted.length];
|
||||
System.arraycopy(iv, 0, payload, 0, iv.length);
|
||||
System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length);
|
||||
|
||||
preferences(context).edit()
|
||||
.putString(FIELD_SESSION, Base64.encodeToString(payload, Base64.NO_WRAP))
|
||||
.apply();
|
||||
} catch (Exception error) {
|
||||
// 密钥不可用时不保留任何明文,直接清空,交给上层重新登录
|
||||
clearSession(context);
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取并解密会话;不存在或解密失败返回 null */
|
||||
public static String readSession(Context context) {
|
||||
String stored = preferences(context).getString(FIELD_SESSION, null);
|
||||
if (stored == null || stored.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
byte[] payload = Base64.decode(stored, Base64.NO_WRAP);
|
||||
if (payload.length <= IV_BYTES) {
|
||||
return null;
|
||||
}
|
||||
byte[] iv = new byte[IV_BYTES];
|
||||
System.arraycopy(payload, 0, iv, 0, IV_BYTES);
|
||||
byte[] encrypted = new byte[payload.length - IV_BYTES];
|
||||
System.arraycopy(payload, IV_BYTES, encrypted, 0, encrypted.length);
|
||||
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), new GCMParameterSpec(TAG_BITS, iv));
|
||||
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
|
||||
} catch (Exception error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 清除会话,同时丢弃密钥,避免残留可用密文 */
|
||||
public static void clearSession(Context context) {
|
||||
preferences(context).edit().remove(FIELD_SESSION).apply();
|
||||
try {
|
||||
KeyStore keyStore = KeyStore.getInstance(KEY_STORE);
|
||||
keyStore.load(null);
|
||||
if (keyStore.containsAlias(KEY_ALIAS)) {
|
||||
keyStore.deleteEntry(KEY_ALIAS);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 密钥清理失败不影响业务流程
|
||||
}
|
||||
}
|
||||
|
||||
private static SharedPreferences preferences(Context context) {
|
||||
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
private static SecretKey getOrCreateKey() throws Exception {
|
||||
KeyStore keyStore = KeyStore.getInstance(KEY_STORE);
|
||||
keyStore.load(null);
|
||||
if (keyStore.containsAlias(KEY_ALIAS)) {
|
||||
return (SecretKey) keyStore.getKey(KEY_ALIAS, null);
|
||||
}
|
||||
|
||||
KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEY_STORE);
|
||||
generator.init(
|
||||
new KeyGenParameterSpec.Builder(
|
||||
KEY_ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(KEY_BITS)
|
||||
.build()
|
||||
);
|
||||
return generator.generateKey();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
|
||||
import androidx.core.content.FileProvider;
|
||||
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* 系统分享。
|
||||
*
|
||||
* <p>FileProvider 只放行 cache / files / external-files 三个目录,外部存储的路径会抛异常,
|
||||
* 调用方需要先把文件落到应用私有目录(下载器就是这么做的)。
|
||||
*/
|
||||
final class ShareHelper {
|
||||
|
||||
private ShareHelper() {
|
||||
}
|
||||
|
||||
static void share(Activity activity, PluginCall call, String path) {
|
||||
File file = new File(MediaInfo.stripScheme(path));
|
||||
if (!file.isFile()) {
|
||||
call.reject("文件不存在:" + path, "file_not_found");
|
||||
return;
|
||||
}
|
||||
|
||||
Uri uri;
|
||||
try {
|
||||
uri = FileProvider.getUriForFile(
|
||||
activity,
|
||||
activity.getPackageName() + ".fileprovider",
|
||||
file
|
||||
);
|
||||
} catch (Exception error) {
|
||||
call.reject("文件不在可分享目录内,请先下载到应用缓存", "file_not_shareable");
|
||||
return;
|
||||
}
|
||||
|
||||
String mimeType = call.getString("mimeType", MediaInfo.guessMimeType(file.getName()));
|
||||
String title = call.getString("title", "分享");
|
||||
String text = call.getString("text");
|
||||
|
||||
Intent intent = new Intent(Intent.ACTION_SEND);
|
||||
intent.setType(mimeType);
|
||||
intent.putExtra(Intent.EXTRA_STREAM, uri);
|
||||
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
if (text != null && !text.isEmpty()) {
|
||||
intent.putExtra(Intent.EXTRA_TEXT, text);
|
||||
}
|
||||
|
||||
Intent chooser = Intent.createChooser(intent, title);
|
||||
chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
try {
|
||||
activity.startActivity(chooser);
|
||||
call.resolve();
|
||||
} catch (Exception error) {
|
||||
call.reject("无法打开分享面板", "activity_not_found");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.media.AudioManager;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.Network;
|
||||
import android.net.NetworkCapabilities;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.PowerManager;
|
||||
import android.provider.Settings;
|
||||
import android.view.WindowManager;
|
||||
import android.webkit.CookieManager;
|
||||
import android.webkit.WebStorage;
|
||||
import android.webkit.WebView;
|
||||
|
||||
import com.getcapacitor.JSObject;
|
||||
|
||||
/**
|
||||
* 环境感知与设备控制。
|
||||
*
|
||||
* <p>这些能力单看都不起眼,但缺了它们,前端就没法回答三个基本问题:
|
||||
* 「用户还在用 App 吗」「网断了吗」「权限被拒了还能不能救」。
|
||||
*
|
||||
* <p>前台判定没有用 Activity 的 onResume/onPause —— 打开扫码页、语音页都会让
|
||||
* MainActivity pause,会被误判成切到后台。这里改用 Activity 计数:只要有任意一个
|
||||
* 自己的 Activity 处于 started 状态,就算前台。
|
||||
*/
|
||||
final class SystemHelper implements Application.ActivityLifecycleCallbacks {
|
||||
|
||||
private final NativeKitPlugin plugin;
|
||||
private final Context context;
|
||||
|
||||
/**
|
||||
* 插件加载时必然处在前台(Bridge 只在 Activity 创建时构建),先记 1。
|
||||
*
|
||||
* <p>重建 Activity(restartApp)时更明显:新插件实例注册回调晚于新 Activity 的
|
||||
* onStart,如果从 0 开始计,就再也收不到那次 started,会一直报「后台」。
|
||||
* 所以第一次 onActivityStarted 只用来对齐这个初始值,不重复计数。
|
||||
*/
|
||||
private int startedCount = 1;
|
||||
private boolean primed = false;
|
||||
private ConnectivityManager.NetworkCallback networkCallback;
|
||||
private boolean lastConnected = true;
|
||||
private String lastType = "none";
|
||||
|
||||
SystemHelper(NativeKitPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.context = plugin.getContext().getApplicationContext();
|
||||
}
|
||||
|
||||
void start() {
|
||||
try {
|
||||
Application application = (Application) context;
|
||||
application.registerActivityLifecycleCallbacks(this);
|
||||
} catch (Exception ignored) {
|
||||
// 非 Application 上下文时跳过,不影响其他能力
|
||||
}
|
||||
registerNetwork();
|
||||
}
|
||||
|
||||
void stop() {
|
||||
try {
|
||||
Application application = (Application) context;
|
||||
application.unregisterActivityLifecycleCallbacks(this);
|
||||
} catch (Exception ignored) {
|
||||
// 未注册成功时忽略
|
||||
}
|
||||
unregisterNetwork();
|
||||
}
|
||||
|
||||
// ---------- 前台状态 ----------
|
||||
|
||||
/**
|
||||
* 是否在前台。
|
||||
*
|
||||
* <p>优先用 Activity 计数(事件由它驱动,时序准确);计数归零时再用进程 importance 兜底。
|
||||
* 重建场景下新插件实例注册回调晚于新 Activity 的 onStart,计数会落不到 1,
|
||||
* 只靠计数会一直误报后台。
|
||||
*/
|
||||
boolean isActive() {
|
||||
if (0 < startedCount) {
|
||||
return true;
|
||||
}
|
||||
return isProcessForeground();
|
||||
}
|
||||
|
||||
private boolean isProcessForeground() {
|
||||
try {
|
||||
android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(
|
||||
Context.ACTIVITY_SERVICE
|
||||
);
|
||||
if (manager == null) {
|
||||
return false;
|
||||
}
|
||||
java.util.List<android.app.ActivityManager.RunningAppProcessInfo> processes =
|
||||
manager.getRunningAppProcesses();
|
||||
if (processes == null) {
|
||||
return false;
|
||||
}
|
||||
for (android.app.ActivityManager.RunningAppProcessInfo info : processes) {
|
||||
if (context.getPackageName().equals(info.processName)) {
|
||||
return info.importance == android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 查询被 ROM 限制时按后台处理
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityStarted(Activity activity) {
|
||||
if (!primed) {
|
||||
primed = true;
|
||||
return;
|
||||
}
|
||||
startedCount++;
|
||||
if (1 == startedCount) {
|
||||
emitAppState(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityStopped(Activity activity) {
|
||||
// 还没对齐初始值,这次 stop 来自被 restartApp 替换掉的旧 Activity,不能计数
|
||||
if (!primed) {
|
||||
return;
|
||||
}
|
||||
startedCount--;
|
||||
if (startedCount <= 0) {
|
||||
startedCount = 0;
|
||||
emitAppState(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityResumed(Activity activity) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityPaused(Activity activity) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityDestroyed(Activity activity) {
|
||||
}
|
||||
|
||||
private void emitAppState(boolean active) {
|
||||
JSObject payload = new JSObject();
|
||||
payload.put("isActive", active);
|
||||
plugin.emit("appStateChange", payload);
|
||||
}
|
||||
|
||||
// ---------- 网络 ----------
|
||||
|
||||
void getNetworkStatus(com.getcapacitor.PluginCall call) {
|
||||
call.resolve(buildNetworkStatus());
|
||||
}
|
||||
|
||||
private JSObject buildNetworkStatus() {
|
||||
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
JSObject result = new JSObject();
|
||||
if (manager == null) {
|
||||
result.put("connected", false);
|
||||
result.put("type", "none");
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
Network network = manager.getActiveNetwork();
|
||||
NetworkCapabilities capabilities = manager.getNetworkCapabilities(network);
|
||||
boolean connected = capabilities != null
|
||||
&& capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
|
||||
result.put("connected", connected);
|
||||
result.put("type", networkType(capabilities));
|
||||
} catch (Exception error) {
|
||||
result.put("connected", false);
|
||||
result.put("type", "none");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void registerNetwork() {
|
||||
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
if (manager == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
JSObject current = buildNetworkStatus();
|
||||
lastConnected = current.optBoolean("connected", false);
|
||||
lastType = current.getString("type", "none");
|
||||
|
||||
networkCallback = new ConnectivityManager.NetworkCallback() {
|
||||
@Override
|
||||
public void onAvailable(Network network) {
|
||||
publishNetwork();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLost(Network network) {
|
||||
publishNetwork();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
|
||||
publishNetwork();
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
manager.registerDefaultNetworkCallback(networkCallback);
|
||||
} catch (Exception error) {
|
||||
networkCallback = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void unregisterNetwork() {
|
||||
if (networkCallback == null) {
|
||||
return;
|
||||
}
|
||||
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
try {
|
||||
if (manager != null) {
|
||||
manager.unregisterNetworkCallback(networkCallback);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 已注销时忽略
|
||||
}
|
||||
networkCallback = null;
|
||||
}
|
||||
|
||||
/** 只在状态真正变化时派发,避免每个网络抖动都打一次桥接 */
|
||||
private void publishNetwork() {
|
||||
JSObject status = buildNetworkStatus();
|
||||
boolean connected = status.optBoolean("connected", false);
|
||||
String type = status.getString("type", "none");
|
||||
if (connected == lastConnected && type.equals(lastType)) {
|
||||
return;
|
||||
}
|
||||
lastConnected = connected;
|
||||
lastType = type;
|
||||
plugin.emit("networkStatusChange", status);
|
||||
}
|
||||
|
||||
private static String networkType(NetworkCapabilities capabilities) {
|
||||
if (capabilities == null) {
|
||||
return "none";
|
||||
}
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
|
||||
return "wifi";
|
||||
}
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
|
||||
return "cellular";
|
||||
}
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
|
||||
return "ethernet";
|
||||
}
|
||||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
|
||||
return "vpn";
|
||||
}
|
||||
return "other";
|
||||
}
|
||||
|
||||
// ---------- 系统设置跳转 ----------
|
||||
|
||||
void openAppSettings(com.getcapacitor.PluginCall call) {
|
||||
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.setData(Uri.parse("package:" + context.getPackageName()));
|
||||
launch(call, intent, "无法打开应用设置");
|
||||
}
|
||||
|
||||
void openNotificationSettings(com.getcapacitor.PluginCall call) {
|
||||
Intent intent;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
|
||||
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
|
||||
} else {
|
||||
intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.setData(Uri.parse("package:" + context.getPackageName()));
|
||||
}
|
||||
launch(call, intent, "无法打开通知设置");
|
||||
}
|
||||
|
||||
void openBatteryOptimizationSettings(com.getcapacitor.PluginCall call) {
|
||||
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
|
||||
intent.setData(Uri.parse("package:" + context.getPackageName()));
|
||||
try {
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
context.startActivity(intent);
|
||||
call.resolve();
|
||||
return;
|
||||
} catch (Exception ignored) {
|
||||
// 部分 ROM 不认这个 action,退回到电池优化列表页
|
||||
}
|
||||
|
||||
Intent fallback = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
|
||||
launch(call, fallback, "无法打开电池优化设置");
|
||||
}
|
||||
|
||||
boolean isIgnoringBatteryOptimizations() {
|
||||
PowerManager manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||
return manager != null && manager.isIgnoringBatteryOptimizations(context.getPackageName());
|
||||
}
|
||||
|
||||
private void launch(com.getcapacitor.PluginCall call, Intent intent, String message) {
|
||||
try {
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
context.startActivity(intent);
|
||||
call.resolve();
|
||||
} catch (Exception error) {
|
||||
call.reject(message, "activity_not_found");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 设备 ----------
|
||||
|
||||
/**
|
||||
* ANDROID_ID。
|
||||
*
|
||||
* <p>Android 8 起按「签名 + 用户」隔离,同一台设备重装、清数据都不变,
|
||||
* 恢复出厂或换签名才会变,是当前唯一稳定可用的设备标识。
|
||||
*/
|
||||
String getAndroidId() {
|
||||
try {
|
||||
String id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
|
||||
return id == null ? "" : id;
|
||||
} catch (Exception error) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
String getRingerMode() {
|
||||
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
|
||||
if (manager == null) {
|
||||
return "normal";
|
||||
}
|
||||
switch (manager.getRingerMode()) {
|
||||
case AudioManager.RINGER_MODE_SILENT:
|
||||
return "silent";
|
||||
case AudioManager.RINGER_MODE_VIBRATE:
|
||||
return "vibrate";
|
||||
default:
|
||||
return "normal";
|
||||
}
|
||||
}
|
||||
|
||||
/** 只在当前 Activity 上生效,离开页面要关掉,否则一直亮屏耗电 */
|
||||
void setKeepAwake(Activity activity, boolean enabled) {
|
||||
if (activity == null) {
|
||||
return;
|
||||
}
|
||||
if (enabled) {
|
||||
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
} else {
|
||||
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
}
|
||||
}
|
||||
|
||||
void setOrientation(Activity activity, String orientation) {
|
||||
if (activity == null) {
|
||||
return;
|
||||
}
|
||||
int requested;
|
||||
if ("portrait".equals(orientation)) {
|
||||
requested = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
|
||||
} else if ("landscape".equals(orientation)) {
|
||||
requested = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
|
||||
} else {
|
||||
requested = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
|
||||
}
|
||||
activity.setRequestedOrientation(requested);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重启应用界面。
|
||||
*
|
||||
* <p>不是杀进程。Android 10 起禁止后台启动 Activity,靠 AlarmManager 的
|
||||
* PendingIntent 把进程拉回来的做法会被系统拦掉,实测杀了就再也起不来。
|
||||
* 这里改成清空任务栈重建 MainActivity:进程不换,但 WebView 会重新加载、
|
||||
* Bridge 会重建,对「切账号彻底重置」已经够用。
|
||||
*/
|
||||
void restartApp(Activity activity) {
|
||||
if (activity == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Intent intent = new Intent(activity, activity.getClass());
|
||||
intent.addFlags(
|
||||
Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
| Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
| Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||||
);
|
||||
activity.startActivity(intent);
|
||||
activity.finishAffinity();
|
||||
} catch (Exception error) {
|
||||
activity.recreate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清 WebView 缓存。
|
||||
*
|
||||
* <p>{@code storage} 为真时会连 localStorage / Cookie 一起清 —— 登录态、主题、
|
||||
* 热更记录都会没,只在排查白屏或切账号彻底重置时用。
|
||||
*/
|
||||
void clearWebCache(WebView webView, boolean storage) {
|
||||
if (webView != null) {
|
||||
webView.clearCache(true);
|
||||
webView.clearFormData();
|
||||
}
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
CookieManager.getInstance().removeAllCookies(null);
|
||||
CookieManager.getInstance().flush();
|
||||
WebStorage.getInstance().deleteAllData();
|
||||
android.webkit.WebViewDatabase.getInstance(context).clearHttpAuthUsernamePassword();
|
||||
} catch (Exception ignored) {
|
||||
// 单项清理失败不影响其余
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
package com.imyeyu.gao.customer.nativekit;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.speech.RecognitionListener;
|
||||
import android.speech.RecognizerIntent;
|
||||
import android.speech.SpeechRecognizer;
|
||||
|
||||
import androidx.activity.result.ActivityResult;
|
||||
|
||||
import com.getcapacitor.PluginCall;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* 语音输入。
|
||||
*
|
||||
* <p>Web Speech API 在 Android WebView 里没有实现(Chromium 把 SpeechRecognition 编译排除在外),
|
||||
* 只能走原生。两条通道:
|
||||
*
|
||||
* <ul>
|
||||
* <li>A:{@link SpeechRecognizer} —— 可控,能拿 partial 结果(边说边上屏),但需要 RECORD_AUDIO</li>
|
||||
* <li>B:{@link RecognizerIntent#ACTION_RECOGNIZE_SPEECH} —— 不需要权限,覆盖面更广,
|
||||
* 但拿不到中间结果,且会压一层 Activity</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>国产 ROM 上 A 的 {@code isRecognitionAvailable()} 常为 false,但系统语音助手能响应 B,
|
||||
* 所以不能只判 A。
|
||||
*/
|
||||
final class VoiceInput implements RecognitionListener {
|
||||
|
||||
private static final String DEFAULT_LANG = "zh-CN";
|
||||
private static final int ERROR_LANGUAGE_NOT_SUPPORTED = 12;
|
||||
private static final int ERROR_LANGUAGE_UNAVAILABLE = 13;
|
||||
|
||||
private final NativeKitPlugin plugin;
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private SpeechRecognizer recognizer;
|
||||
/** 跨线程读写:start 在桥接线程,onResults 在主线程 */
|
||||
private volatile PluginCall activeCall;
|
||||
private String language;
|
||||
private boolean wantPartial;
|
||||
private boolean preferOffline;
|
||||
private boolean offlineRetried;
|
||||
private volatile boolean listening;
|
||||
|
||||
VoiceInput(NativeKitPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
// ---------- 探测 ----------
|
||||
|
||||
void available(PluginCall call) {
|
||||
Context context = plugin.getContext();
|
||||
com.getcapacitor.JSObject result = new com.getcapacitor.JSObject();
|
||||
|
||||
boolean recognizerReady = SpeechRecognizer.isRecognitionAvailable(context);
|
||||
boolean intentReady = canHandleIntent(context);
|
||||
|
||||
String channel = recognizerReady ? "recognizer" : (intentReady ? "intent" : "none");
|
||||
result.put("channel", channel);
|
||||
result.put("engine", recognizerReady ? "system" : "");
|
||||
call.resolve(result);
|
||||
}
|
||||
|
||||
private static boolean canHandleIntent(Context context) {
|
||||
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
|
||||
// Android 11 起受包可见性限制,没有 queries 声明时这里永远返回 null
|
||||
return intent.resolveActivity(context.getPackageManager()) != null;
|
||||
}
|
||||
|
||||
// ---------- 开始 ----------
|
||||
|
||||
void start(PluginCall call) {
|
||||
if (activeCall != null) {
|
||||
call.reject("上一次识别尚未结束", "busy");
|
||||
return;
|
||||
}
|
||||
|
||||
Context context = plugin.getContext();
|
||||
activeCall = call;
|
||||
language = call.getString("lang", DEFAULT_LANG);
|
||||
wantPartial = !Boolean.FALSE.equals(call.getBoolean("partial", true));
|
||||
preferOffline = Boolean.TRUE.equals(call.getBoolean("preferOffline", false));
|
||||
offlineRetried = false;
|
||||
|
||||
if (SpeechRecognizer.isRecognitionAvailable(context)) {
|
||||
if (!plugin.hasMicrophonePermission()) {
|
||||
plugin.requestMicrophonePermission(call, "voicePermissionResult");
|
||||
return;
|
||||
}
|
||||
startRecognizer();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canHandleIntent(context)) {
|
||||
finish();
|
||||
call.reject("当前设备没有可用的语音识别服务", "unavailable");
|
||||
return;
|
||||
}
|
||||
startIntent();
|
||||
}
|
||||
|
||||
/** 权限回调后继续;由 NativeKitPlugin 的 @PermissionCallback 转发 */
|
||||
void onPermissionResult(PluginCall call) {
|
||||
if (!plugin.hasMicrophonePermission()) {
|
||||
finish();
|
||||
call.reject("未授予麦克风权限", "permission_denied");
|
||||
return;
|
||||
}
|
||||
startRecognizer();
|
||||
}
|
||||
|
||||
private void startRecognizer() {
|
||||
if (activeCall == null) {
|
||||
return;
|
||||
}
|
||||
plugin.emitVoiceState("listening");
|
||||
|
||||
mainHandler.post(() -> {
|
||||
try {
|
||||
destroyRecognizer();
|
||||
recognizer = SpeechRecognizer.createSpeechRecognizer(plugin.getContext());
|
||||
recognizer.setRecognitionListener(this);
|
||||
|
||||
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, wantPartial);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
|
||||
if (preferOffline) {
|
||||
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true);
|
||||
}
|
||||
|
||||
listening = true;
|
||||
recognizer.startListening(intent);
|
||||
} catch (Exception error) {
|
||||
fail("start_failed", "无法启动语音识别:" + error.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void startIntent() {
|
||||
if (activeCall == null) {
|
||||
return;
|
||||
}
|
||||
plugin.markInternalNavigation();
|
||||
plugin.emitVoiceState("listening");
|
||||
|
||||
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
|
||||
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请说出要输入的内容");
|
||||
plugin.startVoiceIntent(activeCall, intent);
|
||||
}
|
||||
|
||||
/** Intent 通道返回,由 NativeKitPlugin 的 @ActivityCallback 转发 */
|
||||
void onIntentResult(PluginCall call, ActivityResult result) {
|
||||
plugin.emitVoiceState("idle");
|
||||
|
||||
if (call == null) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
if (result.getResultCode() != android.app.Activity.RESULT_OK || result.getData() == null) {
|
||||
finish();
|
||||
call.reject("已取消语音输入", "cancelled");
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayList<String> texts = result
|
||||
.getData()
|
||||
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
|
||||
String text = texts == null || texts.isEmpty() ? "" : texts.get(0);
|
||||
if (text == null) {
|
||||
text = "";
|
||||
}
|
||||
if (text.trim().isEmpty()) {
|
||||
finish();
|
||||
call.reject("没有识别到内容", "no_match");
|
||||
return;
|
||||
}
|
||||
|
||||
com.getcapacitor.JSObject payload = new com.getcapacitor.JSObject();
|
||||
payload.put("text", text.trim());
|
||||
finish();
|
||||
call.resolve(payload);
|
||||
}
|
||||
|
||||
// ---------- 停止与取消 ----------
|
||||
|
||||
void stop(PluginCall call) {
|
||||
mainHandler.post(() -> {
|
||||
if (recognizer != null && listening) {
|
||||
try {
|
||||
recognizer.stopListening();
|
||||
} catch (Exception ignored) {
|
||||
// 已经结束的识别再 stop 会抛异常,忽略
|
||||
}
|
||||
}
|
||||
});
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
void cancel(PluginCall call) {
|
||||
PluginCall pending = activeCall;
|
||||
mainHandler.post(this::destroyRecognizer);
|
||||
plugin.emitVoiceState("idle");
|
||||
activeCall = null;
|
||||
if (pending != null) {
|
||||
pending.reject("已取消语音输入", "cancelled");
|
||||
}
|
||||
call.resolve();
|
||||
}
|
||||
|
||||
void release() {
|
||||
mainHandler.post(this::destroyRecognizer);
|
||||
activeCall = null;
|
||||
}
|
||||
|
||||
// ---------- RecognitionListener ----------
|
||||
|
||||
@Override
|
||||
public void onReadyForSpeech(Bundle params) {
|
||||
plugin.emitVoiceState("listening");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBeginningOfSpeech() {
|
||||
plugin.emitVoiceState("listening");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRmsChanged(float rmsdB) {
|
||||
// 波形由前端根据 voiceState 自己画,这里不做转发,避免桥接被高频回调打满
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBufferReceived(byte[] buffer) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEndOfSpeech() {
|
||||
plugin.emitVoiceState("processing");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(int error) {
|
||||
listening = false;
|
||||
|
||||
// 指定离线但引擎不支持时,退回联网模式再试一次
|
||||
if (preferOffline && !offlineRetried
|
||||
&& (error == ERROR_LANGUAGE_NOT_SUPPORTED || error == ERROR_LANGUAGE_UNAVAILABLE || error == SpeechRecognizer.ERROR_CLIENT)) {
|
||||
offlineRetried = true;
|
||||
preferOffline = false;
|
||||
mainHandler.postDelayed(() -> {
|
||||
if (activeCall != null) {
|
||||
startRecognizer();
|
||||
}
|
||||
}, 120);
|
||||
return;
|
||||
}
|
||||
|
||||
// 引擎忙:销毁重建后再给一次机会
|
||||
if (error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY && !offlineRetried) {
|
||||
offlineRetried = true;
|
||||
mainHandler.postDelayed(() -> {
|
||||
if (activeCall != null) {
|
||||
startRecognizer();
|
||||
}
|
||||
}, 250);
|
||||
return;
|
||||
}
|
||||
|
||||
fail(errorName(error), "语音识别失败:" + errorName(error));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResults(Bundle results) {
|
||||
listening = false;
|
||||
String text = firstResult(results);
|
||||
if (text.isEmpty()) {
|
||||
fail("no_match", "没有识别到内容");
|
||||
return;
|
||||
}
|
||||
|
||||
float[] scores = results == null
|
||||
? null
|
||||
: results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);
|
||||
|
||||
com.getcapacitor.JSObject payload = new com.getcapacitor.JSObject();
|
||||
payload.put("text", text);
|
||||
if (scores != null && 0 < scores.length) {
|
||||
payload.put("confidence", scores[0]);
|
||||
}
|
||||
|
||||
PluginCall pending = activeCall;
|
||||
finish();
|
||||
plugin.emitVoiceState("idle");
|
||||
if (pending != null) {
|
||||
pending.resolve(payload);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPartialResults(Bundle partialResults) {
|
||||
if (!wantPartial) {
|
||||
return;
|
||||
}
|
||||
String text = firstResult(partialResults);
|
||||
if (!text.isEmpty()) {
|
||||
plugin.emitVoicePartial(text);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(int eventType, Bundle params) {
|
||||
}
|
||||
|
||||
// ---------- 内部 ----------
|
||||
|
||||
private static String firstResult(Bundle bundle) {
|
||||
if (bundle == null) {
|
||||
return "";
|
||||
}
|
||||
ArrayList<String> texts = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
|
||||
if (texts == null || texts.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
String text = texts.get(0);
|
||||
return text == null ? "" : text.trim();
|
||||
}
|
||||
|
||||
private void fail(String code, String message) {
|
||||
PluginCall pending = activeCall;
|
||||
finish();
|
||||
plugin.emitVoiceState("idle");
|
||||
if (pending != null) {
|
||||
pending.reject(message, code);
|
||||
}
|
||||
}
|
||||
|
||||
private void finish() {
|
||||
listening = false;
|
||||
activeCall = null;
|
||||
mainHandler.post(this::destroyRecognizer);
|
||||
}
|
||||
|
||||
private void destroyRecognizer() {
|
||||
if (recognizer == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
recognizer.cancel();
|
||||
recognizer.destroy();
|
||||
} catch (Exception ignored) {
|
||||
// 已经销毁时 destroy 会抛异常,忽略
|
||||
}
|
||||
recognizer = null;
|
||||
}
|
||||
|
||||
private static String errorName(int code) {
|
||||
switch (code) {
|
||||
case SpeechRecognizer.ERROR_AUDIO:
|
||||
return "audio";
|
||||
case SpeechRecognizer.ERROR_CLIENT:
|
||||
return "client";
|
||||
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
|
||||
return "permission_denied";
|
||||
case SpeechRecognizer.ERROR_NETWORK:
|
||||
return "network";
|
||||
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
|
||||
return "network_timeout";
|
||||
case SpeechRecognizer.ERROR_NO_MATCH:
|
||||
return "no_match";
|
||||
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
|
||||
return "busy";
|
||||
case SpeechRecognizer.ERROR_SERVER:
|
||||
return "server";
|
||||
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
|
||||
return "speech_timeout";
|
||||
case ERROR_LANGUAGE_NOT_SUPPORTED:
|
||||
return "language_not_supported";
|
||||
case ERROR_LANGUAGE_UNAVAILABLE:
|
||||
return "language_unavailable";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 8.0 KiB |
|
Before Width: | Height: | Size: 8.6 KiB After Width: | Height: | Size: 4.9 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 28 KiB |
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 通知栏小图标必须是纯白单色,彩色资源会被系统渲染成灰块 -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.9,2 2,2zM18,16v-5c0,-3.07 -1.63,-5.64 -4.5,-6.32V4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.64,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" />
|
||||
</vector>
|
||||
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 6.2 KiB |
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 9.0 KiB After Width: | Height: | Size: 8.7 KiB |
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 6.4 KiB After Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 7.8 KiB After Width: | Height: | Size: 9.0 KiB |
|
Before Width: | Height: | Size: 8.5 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 12 KiB |
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#0F766E</color>
|
||||
</resources>
|
||||
<color name="ic_launcher_background">#FFFFFF</color>
|
||||
</resources>
|
||||
|
||||
@@ -19,4 +19,17 @@
|
||||
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
||||
<item name="android:background">@drawable/splash</item>
|
||||
</style>
|
||||
|
||||
<!--
|
||||
相机页:全屏黑底,系统栏透明。
|
||||
不能用 AppTheme.NoActionBar,它的 android:background=@null 会让取景前的瞬间透出桌面。
|
||||
-->
|
||||
<style name="AppTheme.CameraKit" parent="Theme.AppCompat.NoActionBar">
|
||||
<item name="windowActionBar">false</item>
|
||||
<item name="windowNoTitle">true</item>
|
||||
<item name="android:windowBackground">#000000</item>
|
||||
<item name="android:statusBarColor">#000000</item>
|
||||
<item name="android:navigationBarColor">#000000</item>
|
||||
<item name="android:windowLightStatusBar">false</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,5 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
FileProvider 只放行应用自己的目录。
|
||||
|
||||
原先的 external-path path="." 会把整个外部存储暴露给任何拿到 URI 的调用方,
|
||||
分享与打印都不需要这个范围。ShellUpdater 使用 cacheDir/shell-updates,由 cache-path 覆盖。
|
||||
-->
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
||||
<cache-path name="nativekit_cache" path="." />
|
||||
<files-path name="nativekit_files" path="." />
|
||||
<external-files-path name="nativekit_external_files" path="." />
|
||||
</paths>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# 发版签名凭证(复制为 android/keystore.properties 后填写,该文件已 gitignore)
|
||||
# storeFile 相对于 android/ 目录
|
||||
storeFile=../android.keystore
|
||||
keyAlias=gao-customer
|
||||
storePassword=
|
||||
keyPassword=
|
||||
@@ -1,5 +1,5 @@
|
||||
ext {
|
||||
minSdkVersion = 24
|
||||
minSdkVersion = 29
|
||||
compileSdkVersion = 36
|
||||
targetSdkVersion = 36
|
||||
androidxActivityVersion = '1.11.0'
|
||||
@@ -9,8 +9,12 @@ ext {
|
||||
androidxFragmentVersion = '1.8.9'
|
||||
coreSplashScreenVersion = '1.2.0'
|
||||
androidxWebkitVersion = '1.14.0'
|
||||
// 原生能力预埋:相机、条码解码、生物识别
|
||||
androidxCameraVersion = '1.4.2'
|
||||
zxingVersion = '3.5.3'
|
||||
androidxBiometricVersion = '1.1.0'
|
||||
junitVersion = '4.13.2'
|
||||
androidxJunitVersion = '1.3.0'
|
||||
androidxEspressoCoreVersion = '3.7.0'
|
||||
cordovaAndroidVersion = '14.0.1'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@
|
||||
// biome-ignore lint: disable
|
||||
export {}
|
||||
declare global {
|
||||
const DialogPlugin: typeof import('tdesign-mobile-vue')['DialogPlugin']
|
||||
const EffectScope: typeof import('vue')['EffectScope']
|
||||
const THUMBNAIL_WIDTH_PARAM: typeof import('tdesign-mobile-vue')['HUMBNAIL_WIDTH_PARAM']
|
||||
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
|
||||
const computed: typeof import('vue')['computed']
|
||||
const createApp: typeof import('vue')['createApp']
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-labelledby="gaoRoundTitle gaoRoundDesc">
|
||||
<title id="gaoRoundTitle">糕 · 护理门店管理</title>
|
||||
<desc id="gaoRoundDesc">字母 G 环抱一颗心的柔化候选:收笔圆角 22、根部转角 14、缺口端 6,青绿渐变底色</desc>
|
||||
<defs><linearGradient id="b" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#12907F"/><stop offset=".55" stop-color="#0F7A70"/><stop offset="1" stop-color="#0A655F"/></linearGradient></defs><rect width="512" height="512" rx="114" fill="url(#b)"/>
|
||||
<path d="M403.82 124.13A198 198 0 1 0 454.00 264.00Q454.00 256.00 446.00 256.00L398.00 256.00Q384.00 256.00 384.00 270.00A128 128 0 1 1 350.20 169.13Q354.05 173.72 358.65 169.87L403.08 132.58Q407.68 128.73 403.82 124.13Z" fill="#FFFFFF"/><path d="M314 256H454A198 198 0 0 1 441.21 326H314Q292 326 292 304V278Q292 256 314 256Z" fill="#FFFFFF"/>
|
||||
<path d="M12 21s-8-5.2-8-10.4A4.6 4.6 0 0 1 12 7.6 4.6 4.6 0 0 1 20 10.6C20 15.8 12 21 12 21z" transform="translate(151 198.2) scale(5.75)" fill="#FFFFFF"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-labelledby="gaoSmallTitle gaoSmallDesc">
|
||||
<title id="gaoSmallTitle">糕 · 小尺寸简化图标</title>
|
||||
<desc id="gaoSmallDesc">去掉心形、加粗笔画、收窄留白的 16 至 47 像素专用版本</desc>
|
||||
<rect width="512" height="512" rx="114" fill="#0F766E"/>
|
||||
<path d="M410.6 116.8A208 208 0 1 0 464 256L392 256A136 136 0 1 1 357.1 165Z" fill="#FFFFFF"/>
|
||||
<path d="M300 256H464A208 208 0 0 1 451.1 328H300Z" fill="#FFFFFF"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 546 B |
@@ -0,0 +1,15 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-labelledby="gaoIconTitle gaoIconDesc">
|
||||
<title id="gaoIconTitle">糕 · 护理门店管理</title>
|
||||
<desc id="gaoIconDesc">字母 G 环抱一颗心的品牌图标,照护青底色,48 像素以上使用</desc>
|
||||
<defs>
|
||||
<linearGradient id="gaoIconBg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#12907F"/>
|
||||
<stop offset=".55" stop-color="#0F7A70"/>
|
||||
<stop offset="1" stop-color="#0A655F"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="512" height="512" rx="114" fill="url(#gaoIconBg)"/>
|
||||
<path d="M407.7 128.7A198 198 0 1 0 454 256L384 256A128 128 0 1 1 354.1 173.7Z" fill="#FFFFFF"/>
|
||||
<path d="M292 256H454A198 198 0 0 1 441.2 326H292Z" fill="#FFFFFF"/>
|
||||
<path d="M12 21s-8-5.2-8-10.4A4.6 4.6 0 0 1 12 7.6 4.6 4.6 0 0 1 20 10.6C20 15.8 12 21 12 21z" transform="translate(151 198.2) scale(5.75)" fill="#FFFFFF"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 944 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="40 40 432 432" width="432" height="432" role="img" aria-labelledby="gaoMarkTitle gaoMarkDesc" style="color:#0F766E">
|
||||
<title id="gaoMarkTitle">糕 · 品牌符号</title>
|
||||
<desc id="gaoMarkDesc">无底色的单色 G 符号,继承 currentColor,用于门头、印刷、深底反白与界面水印</desc>
|
||||
<path d="M407.7 128.7A198 198 0 1 0 454 256L384 256A128 128 0 1 1 354.1 173.7Z" fill="currentColor"/>
|
||||
<path d="M292 256H454A198 198 0 0 1 441.2 326H292Z" fill="currentColor"/>
|
||||
<path d="M12 21s-8-5.2-8-10.4A4.6 4.6 0 0 1 12 7.6 4.6 4.6 0 0 1 20 10.6C20 15.8 12 21 12 21z" transform="translate(151 198.2) scale(5.75)" fill="currentColor"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 703 B |
@@ -10,6 +10,7 @@
|
||||
<meta name="apple-mobile-web-app-title" content="Gao Customer H5" />
|
||||
<meta name="format-detection" content="telephone=no" />
|
||||
<meta name="theme-color" content="#ffffff" />
|
||||
<link rel="icon" type="image/svg+xml" href="/icons/brand.svg" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<link rel="apple-touch-icon" href="/icons/icon-192.png" />
|
||||
<title>糕店客户管理</title>
|
||||
@@ -19,3 +20,4 @@
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
{
|
||||
"name": "gao-customer-h5",
|
||||
"private": true,
|
||||
"version": "1.5.0",
|
||||
"version": "1.6.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host",
|
||||
"build": "pnpm run type-check:publish && vite build",
|
||||
"build:zip": "pnpm run build && powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-zip.ps1",
|
||||
"twa:build": "cd twa && pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 build --manifest=./twa-manifest.json",
|
||||
"twa:update": "cd twa && pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 update --skipVersionUpgrade --manifest=./twa-manifest.json",
|
||||
"twa:validate": "pnpm --config.registry=https://registry.npmjs.org dlx @bubblewrap/cli@1.25.0 validate --url=https://gao.imyeyu.com/",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --ext .ts,.vue",
|
||||
"type-check": "vue-tsc -p tsconfig.app.json --noEmit",
|
||||
@@ -18,7 +15,7 @@
|
||||
"android:sync:prod": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-sync.ps1 -Mode prod",
|
||||
"android:sync": "pnpm run android:sync:prod",
|
||||
"android:open": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-open.ps1",
|
||||
"android:apk": "pnpm run android:sync:prod && cd android && gradlew.bat assembleDebug"
|
||||
"android:apk": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/android-apk.ps1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^8",
|
||||
@@ -26,13 +23,12 @@
|
||||
"@capgo/capacitor-updater": "^8",
|
||||
"@zxing/browser": "^0.1.5",
|
||||
"@zxing/library": "^0.21.3",
|
||||
"browser-image-compression": "^2.0.2",
|
||||
"echarts": "^6.0.0",
|
||||
"echarts-wordcloud": "^2.1.0",
|
||||
"less": "^4.3.0",
|
||||
"pinia": "^3.0.2",
|
||||
"tdesign-mobile-vue": "^1.17.1",
|
||||
"timi-tdesign-mobile": "^1.3.1",
|
||||
"timi-tdesign-mobile": "^1.5.0",
|
||||
"timi-ts": "^1.0.0",
|
||||
"timi-web": "^1.0.2",
|
||||
"timi-web-api": "^1.0.2",
|
||||
|
||||
@@ -28,9 +28,6 @@ importers:
|
||||
'@zxing/library':
|
||||
specifier: ^0.21.3
|
||||
version: 0.21.3
|
||||
browser-image-compression:
|
||||
specifier: ^2.0.2
|
||||
version: 2.0.2
|
||||
echarts:
|
||||
specifier: ^6.0.0
|
||||
version: 6.1.0
|
||||
@@ -47,8 +44,8 @@ importers:
|
||||
specifier: ^1.17.1
|
||||
version: 1.17.1(patch_hash=c98db305008fbfd00046666ca890e1c6cb88257c0619418694689cddf8cd78c3)(vue@3.5.40(typescript@5.8.3))
|
||||
timi-tdesign-mobile:
|
||||
specifier: ^1.3.1
|
||||
version: 1.3.1(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3))
|
||||
specifier: ^1.5.0
|
||||
version: 1.5.0(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3))
|
||||
timi-ts:
|
||||
specifier: ^1.0.0
|
||||
version: 1.0.0
|
||||
@@ -1424,9 +1421,6 @@ packages:
|
||||
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
browser-image-compression@2.0.2:
|
||||
resolution: {integrity: sha512-pBLlQyUf6yB8SmmngrcOw3EoS4RpQ1BcylI3T9Yqn7+4nrQTXJD4sJDe5ODnJdrvNMaio5OicFo75rDyJD2Ucw==}
|
||||
|
||||
buffer-crc32@0.2.13:
|
||||
resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}
|
||||
|
||||
@@ -2748,8 +2742,8 @@ packages:
|
||||
through2@4.0.2:
|
||||
resolution: {integrity: sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==}
|
||||
|
||||
timi-tdesign-mobile@1.3.1:
|
||||
resolution: {integrity: sha512-6hz7MSqseCUyyJzRiyQjymMDfSZ3kJrFP6J5DxHpE1pJ8xeByCzKgELS4CnO4187mqPEx46TtF03qB9XS4Mpuw==}
|
||||
timi-tdesign-mobile@1.5.0:
|
||||
resolution: {integrity: sha512-zp5yGlZaiJsf4QuREbBK7qjqQNteAB7PtWWG98rwGPzEwou6Q/45nEc1CJq47BFsuxjCq+7XIhCFl3eX7GgN6w==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
peerDependencies:
|
||||
vue: ^3.5.0
|
||||
@@ -2904,9 +2898,6 @@ packages:
|
||||
util-deprecate@1.0.2:
|
||||
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
|
||||
|
||||
uzip@0.20201231.0:
|
||||
resolution: {integrity: sha512-OZeJfZP+R0z9D6TmBgLq2LHzSSptGMGDGigGiEe0pr8UBe/7fdflgHlHBNDASTXB5jnFuxHpNaJywSg8YFeGng==}
|
||||
|
||||
v8-compile-cache-lib@3.0.1:
|
||||
resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==}
|
||||
|
||||
@@ -4412,10 +4403,6 @@ snapshots:
|
||||
dependencies:
|
||||
fill-range: 7.1.1
|
||||
|
||||
browser-image-compression@2.0.2:
|
||||
dependencies:
|
||||
uzip: 0.20201231.0
|
||||
|
||||
buffer-crc32@0.2.13: {}
|
||||
|
||||
buffer-from@1.1.2: {}
|
||||
@@ -5849,7 +5836,7 @@ snapshots:
|
||||
dependencies:
|
||||
readable-stream: 3.6.2
|
||||
|
||||
timi-tdesign-mobile@1.3.1(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3)):
|
||||
timi-tdesign-mobile@1.5.0(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue-router@4.5.1(vue@3.5.40(typescript@5.8.3)))(vue@3.5.40(typescript@5.8.3)):
|
||||
dependencies:
|
||||
tdesign-mobile-vue: 1.17.1(patch_hash=c98db305008fbfd00046666ca890e1c6cb88257c0619418694689cddf8cd78c3)(vue@3.5.40(typescript@5.8.3))
|
||||
timi-web: 1.0.2(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.8.3)(vue@3.5.40(typescript@5.8.3))
|
||||
@@ -6052,8 +6039,6 @@ snapshots:
|
||||
|
||||
util-deprecate@1.0.2: {}
|
||||
|
||||
uzip@0.20201231.0: {}
|
||||
|
||||
v8-compile-cache-lib@3.0.1: {}
|
||||
|
||||
validator@13.15.35: {}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
[
|
||||
{
|
||||
"relation": [
|
||||
"delegate_permission/common.handle_all_urls",
|
||||
"delegate_permission/common.use_as_origin"
|
||||
],
|
||||
"target": {
|
||||
"namespace": "android_app",
|
||||
"package_name": "com.imyeyu.gao.customer",
|
||||
"sha256_cert_fingerprints": [
|
||||
"3E:9C:CC:8A:29:71:18:74:BB:56:AA:88:AD:62:E1:F3:AC:F2:70:07:C4:67:D9:32:B8:A2:4B:B7:E7:8E:06:34"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 9.5 KiB After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,89 @@
|
||||
param(
|
||||
[switch]$SkipSync
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
$propertiesPath = Join-Path $root "android\keystore.properties"
|
||||
|
||||
if (-not (Test-Path $propertiesPath)) {
|
||||
Write-Host "缺少 android\keystore.properties:发版包必须用根目录 android.keystore 签名" -ForegroundColor Red
|
||||
Write-Host "照着同目录的 keystore.properties.example 补全后重试"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$properties = @{}
|
||||
Get-Content $propertiesPath | ForEach-Object {
|
||||
$line = $_.Trim()
|
||||
if ($line -and -not $line.StartsWith("#")) {
|
||||
$index = $line.IndexOf("=")
|
||||
if (0 -lt $index) {
|
||||
$properties[$line.Substring(0, $index).Trim()] = $line.Substring($index + 1).Trim()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $properties["storePassword"] -or -not $properties["keyPassword"]) {
|
||||
Write-Host "android\keystore.properties 里的 storePassword / keyPassword 还没填" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
$storeFile = [System.IO.Path]::GetFullPath((Join-Path (Join-Path $root "android") $properties["storeFile"]))
|
||||
if (-not (Test-Path $storeFile)) {
|
||||
Write-Host "找不到签名文件:$storeFile" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not $SkipSync) {
|
||||
& pnpm run android:sync:prod
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
}
|
||||
|
||||
Push-Location (Join-Path $root "android")
|
||||
try {
|
||||
& .\gradlew.bat :app:assembleRelease --console=plain
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
$outputDir = Join-Path $root "android\app\build\outputs\apk\release"
|
||||
$apk = Get-ChildItem $outputDir -Filter "app-release*.apk" -ErrorAction SilentlyContinue |
|
||||
Where-Object { -not $_.Name.Contains("unsigned") } |
|
||||
Select-Object -First 1
|
||||
if (-not $apk) {
|
||||
Write-Host "没有产出已签名的 release 包,检查 android\app\build.gradle 的 signingConfigs" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
$targetDir = Join-Path $root "android\app\release"
|
||||
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
|
||||
$target = Join-Path $targetDir "app-release.apk"
|
||||
Copy-Item $apk.FullName $target -Force
|
||||
|
||||
$gradle = Get-Content (Join-Path $root "android\app\build.gradle") -Raw
|
||||
$versionCode = [regex]::Match($gradle, 'versionCode\s+(\d+)').Groups[1].Value
|
||||
$versionName = [regex]::Match($gradle, 'versionName\s+"([^"]+)"').Groups[1].Value
|
||||
$file = Get-Item $target
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "APK android\app\release\app-release.apk"
|
||||
Write-Host "version $versionName ($versionCode)"
|
||||
Write-Host "size $($file.Length)"
|
||||
Write-Host "sha256 $((Get-FileHash $target -Algorithm SHA256).Hash.ToLower())"
|
||||
|
||||
# 顺手把签名证书打出来,对不上 3E:9C:CC:8A 就说明钥匙用错了
|
||||
$sdk = $env:ANDROID_HOME
|
||||
if (-not $sdk) { $sdk = $env:ANDROID_SDK_ROOT }
|
||||
if (-not $sdk) { $sdk = Join-Path $env:LOCALAPPDATA "Android\Sdk" }
|
||||
$buildTools = Join-Path $sdk "build-tools"
|
||||
if (Test-Path $buildTools) {
|
||||
$latest = Get-ChildItem $buildTools -Directory | Sort-Object Name | Select-Object -Last 1
|
||||
$signer = Join-Path $latest.FullName "apksigner.bat"
|
||||
if (Test-Path $signer) {
|
||||
& $signer verify --print-certs $target | Select-String "SHA-256 digest" | ForEach-Object {
|
||||
Write-Host "cert $($_.Line.Trim())"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ if ($Mode -eq "dev") {
|
||||
$env:VITE_API_BASE_URL = if ($env:ANDROID_API_BASE_URL) {
|
||||
$env:ANDROID_API_BASE_URL
|
||||
} else {
|
||||
"http://192.168.11.14:18091"
|
||||
"http://192.168.11.18:18091"
|
||||
}
|
||||
Write-Host "接口地址(开发):$env:VITE_API_BASE_URL"
|
||||
} else {
|
||||
|
||||
@@ -1,95 +1,66 @@
|
||||
/**
|
||||
* 从 public/icons/icon-512.png 生成 Android 各密度的启动图标
|
||||
*
|
||||
* 传统图标用完整图,圆形图标裁圆,自适应前景留 10% 余量避免被系统裁切
|
||||
*
|
||||
* 运行:node scripts/generate-android-icons.mjs
|
||||
*/
|
||||
import sharp from "sharp";
|
||||
|
||||
const SOURCE = "public/icons/icon-512.png";
|
||||
const RES = "android/app/src/main/res";
|
||||
const source = "public/icons/brand.svg";
|
||||
const res = "android/app/src/main/res";
|
||||
const transparent = { r: 0, g: 0, b: 0, alpha: 0 };
|
||||
const white = { r: 255, g: 255, b: 255, alpha: 1 };
|
||||
|
||||
/** 传统图标边长 */
|
||||
const LEGACY = { mdpi: 48, hdpi: 72, xhdpi: 96, xxhdpi: 144, xxxhdpi: 192 };
|
||||
|
||||
/** 自适应前景边长,108dp 基准 */
|
||||
const FOREGROUND = { mdpi: 108, hdpi: 162, xhdpi: 216, xxhdpi: 324, xxxhdpi: 432 };
|
||||
|
||||
/** 前景内容占画布的比例,低于安全区 66.7%,留余量 */
|
||||
const FOREGROUND_RATIO = 0.9;
|
||||
|
||||
const { data } = await sharp(SOURCE).raw().toBuffer({ resolveWithObject: true });
|
||||
const hex = `#${[data[0], data[1], data[2]].map(v => v.toString(16).padStart(2, "0")).join("")}`;
|
||||
console.log(`图标底色:${hex}`);
|
||||
|
||||
for (const [density, size] of Object.entries(LEGACY)) {
|
||||
const dir = `${RES}/mipmap-${density}`;
|
||||
await sharp(SOURCE).resize(size, size, { fit: "cover" }).png().toFile(`${dir}/ic_launcher.png`);
|
||||
|
||||
const circle = Buffer.from(
|
||||
`<svg width="${size}" height="${size}"><circle cx="${size / 2}" cy="${size / 2}" r="${size / 2}" fill="#fff"/></svg>`
|
||||
);
|
||||
await sharp(SOURCE)
|
||||
.resize(size, size, { fit: "cover" })
|
||||
.composite([{ input: circle, blend: "dest-in" }])
|
||||
.png()
|
||||
.toFile(`${dir}/ic_launcher_round.png`);
|
||||
|
||||
console.log(`${density}: 传统 ${size},圆形 ${size}`);
|
||||
async function render(size, ratio, background = transparent) {
|
||||
const inner = Math.round(size * ratio);
|
||||
const icon = await sharp(source).resize(inner, inner).png().toBuffer();
|
||||
return await sharp({ create: { width: size, height: size, channels: 4, background } })
|
||||
.composite([{ input: icon, gravity: "centre" }]).png().toBuffer();
|
||||
}
|
||||
|
||||
for (const [density, size] of Object.entries(FOREGROUND)) {
|
||||
const inner = Math.round(size * FOREGROUND_RATIO);
|
||||
const offset = Math.round((size - inner) / 2);
|
||||
const scaled = await sharp(SOURCE).resize(inner, inner, { fit: "cover" }).png().toBuffer();
|
||||
await sharp({
|
||||
create: { width: size, height: size, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } }
|
||||
})
|
||||
.composite([{ input: scaled, top: offset, left: offset }])
|
||||
.png()
|
||||
.toFile(`${RES}/mipmap-${density}/ic_launcher_foreground.png`);
|
||||
// 统一图形像素的颜色,通过透明度保留边缘抗锯齿。
|
||||
const { data: pixels, info } = await sharp(await render(1024, 1)).raw().toBuffer({ resolveWithObject: true });
|
||||
const colors = [[8, 127, 131], [157, 223, 201]];
|
||||
for (let i = 0; i < pixels.length; i += 4) {
|
||||
if (pixels[i + 3] === 0) continue;
|
||||
const color = colors.reduce((closest, candidate) => {
|
||||
const distance = candidate.reduce((sum, channel, index) => sum + (channel - pixels[i + index]) ** 2, 0);
|
||||
return distance < closest.distance ? { value: candidate, distance } : closest;
|
||||
}, { value: colors[0], distance: Infinity }).value;
|
||||
for (let channel = 0; channel < 3; channel++) pixels[i + channel] = color[channel];
|
||||
}
|
||||
await sharp(pixels, { raw: info }).png().toFile("public/icons/brand-transparent.png");
|
||||
await sharp(await render(1024, 1, white)).toFile("public/icons/brand-white.png");
|
||||
for (const size of [192, 512]) {
|
||||
await sharp(await render(size, 1, white)).toFile(`public/icons/icon-${size}.png`);
|
||||
}
|
||||
await sharp(await render(512, .8, white)).toFile("public/icons/icon-maskable-512.png");
|
||||
|
||||
console.log(`${density}: 前景 ${size}(内容 ${inner})`);
|
||||
// 按图形实际边界居中;自适应图标的可见区域约为画布的三分之二。
|
||||
const androidMark = await sharp(source).trim({ background: "#00000000", threshold: 1 }).png().toBuffer();
|
||||
async function renderAndroid(size, ratio, background = transparent) {
|
||||
const inner = Math.round(size * ratio);
|
||||
const icon = await sharp(androidMark).resize(inner, inner, { fit: "contain" }).png().toBuffer();
|
||||
return await sharp({ create: { width: size, height: size, channels: 4, background } })
|
||||
.composite([{ input: icon, gravity: "centre" }]).png().toBuffer();
|
||||
}
|
||||
const legacy = { mdpi: 48, hdpi: 72, xhdpi: 96, xxhdpi: 144, xxxhdpi: 192 };
|
||||
const foreground = { mdpi: 108, hdpi: 162, xhdpi: 216, xxhdpi: 324, xxxhdpi: 432 };
|
||||
for (const [density, size] of Object.entries(legacy)) {
|
||||
const dir = `${res}/mipmap-${density}`;
|
||||
const icon = await renderAndroid(size, .66, white);
|
||||
await sharp(icon).toFile(`${dir}/ic_launcher.png`);
|
||||
const circle = Buffer.from(`<svg width="${size}" height="${size}"><circle cx="${size / 2}" cy="${size / 2}" r="${size / 2}" fill="white"/></svg>`);
|
||||
await sharp(icon).composite([{ input: circle, blend: "dest-in" }]).png().toFile(`${dir}/ic_launcher_round.png`);
|
||||
await sharp(await renderAndroid(foreground[density], .44)).toFile(`${dir}/ic_launcher_foreground.png`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动图尺寸,背景铺图标底色,中间放 logo
|
||||
*
|
||||
* 键为 drawable 目录名,值为画布宽高
|
||||
*/
|
||||
const SPLASH = {
|
||||
"drawable": [480, 320],
|
||||
"drawable-land-mdpi": [480, 320],
|
||||
"drawable-land-hdpi": [800, 480],
|
||||
"drawable-land-xhdpi": [1280, 720],
|
||||
"drawable-land-xxhdpi": [1600, 960],
|
||||
"drawable-land-xxxhdpi": [1920, 1280],
|
||||
"drawable-port-mdpi": [320, 480],
|
||||
"drawable-port-hdpi": [480, 800],
|
||||
"drawable-port-xhdpi": [720, 1280],
|
||||
"drawable-port-xxhdpi": [960, 1600],
|
||||
"drawable-port-xxxhdpi": [1280, 1920]
|
||||
const splash = {
|
||||
"drawable": [480, 320], "drawable-land-mdpi": [480, 320], "drawable-land-hdpi": [800, 480],
|
||||
"drawable-land-xhdpi": [1280, 720], "drawable-land-xxhdpi": [1600, 960], "drawable-land-xxxhdpi": [1920, 1280],
|
||||
"drawable-port-mdpi": [320, 480], "drawable-port-hdpi": [480, 800], "drawable-port-xhdpi": [720, 1280],
|
||||
"drawable-port-xxhdpi": [960, 1600], "drawable-port-xxxhdpi": [1280, 1920]
|
||||
};
|
||||
|
||||
/** logo 占短边的比例 */
|
||||
const SPLASH_LOGO_RATIO = 0.28;
|
||||
|
||||
for (const [dir, [width, height]] of Object.entries(SPLASH)) {
|
||||
const logo = Math.round(Math.min(width, height) * SPLASH_LOGO_RATIO);
|
||||
const scaled = await sharp(SOURCE).resize(logo, logo, { fit: "cover" }).png().toBuffer();
|
||||
await sharp({
|
||||
create: { width, height, channels: 3, background: { r: data[0], g: data[1], b: data[2] } }
|
||||
})
|
||||
.composite([{
|
||||
input: scaled,
|
||||
top: Math.round((height - logo) / 2),
|
||||
left: Math.round((width - logo) / 2)
|
||||
}])
|
||||
.png()
|
||||
.toFile(`${RES}/${dir}/splash.png`);
|
||||
|
||||
console.log(`${dir}: ${width}x${height},logo ${logo}`);
|
||||
for (const [dir, [width, height]] of Object.entries(splash)) {
|
||||
const size = Math.round(Math.min(width, height) * .28);
|
||||
const icon = await render(size, 1);
|
||||
await sharp({ create: { width, height, channels: 4, background: white } })
|
||||
.composite([{ input: icon, gravity: "centre" }]).png().toFile(`${res}/${dir}/splash.png`);
|
||||
}
|
||||
|
||||
console.log("完成");
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import sharp from "sharp";
|
||||
|
||||
const light = await readFile("public/icons/brand.svg", "utf8");
|
||||
const dark = light.replaceAll("#087f83", "#4dc9be").replaceAll("#9ddfc9", "#d0f5e7");
|
||||
await writeFile("public/icons/brand-dark.svg", dark, "utf8");
|
||||
|
||||
const { data, info } = await sharp(Buffer.from(dark)).resize(1024, 1024).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
const colors = [[77, 201, 190], [208, 245, 231]];
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
if (data[i + 3] === 0) continue;
|
||||
const color = colors.reduce((closest, candidate) => {
|
||||
const distance = candidate.reduce((sum, channel, index) => sum + (channel - data[i + index]) ** 2, 0);
|
||||
return distance < closest.distance ? { value: candidate, distance } : closest;
|
||||
}, { value: colors[0], distance: Infinity }).value;
|
||||
for (let channel = 0; channel < 3; channel++) data[i + channel] = color[channel];
|
||||
}
|
||||
const icon = await sharp(data, { raw: info }).png().toBuffer();
|
||||
await sharp(icon).toFile("public/icons/brand-dark-transparent.png");
|
||||
await sharp({ create: { width: 1024, height: 1024, channels: 4, background: "#10161f" } })
|
||||
.composite([{ input: icon }]).png().toFile("public/icons/brand-dark-background.png");
|
||||
@@ -45,6 +45,8 @@ watch(
|
||||
const rootElement = document.documentElement;
|
||||
rootElement.classList.toggle("theme-dark", themeMode === "dark");
|
||||
rootElement.dataset.theme = themeMode;
|
||||
const favicon = document.querySelector<HTMLLinkElement>("link[rel='icon']");
|
||||
if (favicon) favicon.href = themeMode === "dark" ? "/icons/brand-dark.svg" : "/icons/brand.svg";
|
||||
void syncSystemBars(themeMode).catch(() => undefined);
|
||||
},
|
||||
{ immediate: true }
|
||||
@@ -81,3 +83,4 @@ onUnmounted(() => {
|
||||
window.removeEventListener("pointerdown", unlockSoundOnUserGesture);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -76,6 +76,17 @@ async function listLedger(page: PointLedgerPage, options?: ListOptions): Promise
|
||||
return await axios.post(`${BASE_URI}/ledger/list`, withCurrentStoreId(page));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按流水 ID 查询积分流水。
|
||||
*
|
||||
* 不传 storeId:服务端按当前登录人的门店范围解析,非全局管理员天然只能查本店。
|
||||
*/
|
||||
async function ledgerDetail(id: string): Promise<PointLedger> {
|
||||
return await axios.post(`${BASE_URI}/ledger/detail`, undefined, {
|
||||
params: { id }
|
||||
});
|
||||
}
|
||||
|
||||
/** 人工调整积分,后端使用 adjustRequestId 保证幂等。 */
|
||||
async function adjust(request: PointAdjustRequest): Promise<void> {
|
||||
await axios.post(`${BASE_URI}/adjust`, withCurrentStoreId(request));
|
||||
@@ -177,6 +188,7 @@ export default {
|
||||
detailByCustomerId,
|
||||
detail,
|
||||
listLedger,
|
||||
ledgerDetail,
|
||||
adjust,
|
||||
ruleList,
|
||||
ruleDetail,
|
||||
|
||||
@@ -26,6 +26,7 @@ import { getCurrentStoreId, withCurrentStoreId } from "@/utils/store";
|
||||
const CONFIG_URI = "/gao/recycle/config";
|
||||
const EXCHANGE_URI = "/gao/recycle/exchange";
|
||||
const ACCOUNT_URI = "/gao/recycle/account";
|
||||
const LEDGER_URI = "/gao/recycle/ledger";
|
||||
const PAYMENT_URI = "/gao/recycle/payment";
|
||||
const STAT_URI = "/gao/recycle/stat";
|
||||
|
||||
@@ -119,9 +120,11 @@ async function accountList(customerId: string): Promise<RecycleAccount[]> {
|
||||
}
|
||||
|
||||
/** 按客户分页查询有余额的回收物及全门店汇总。 */
|
||||
async function accountCustomers(offset: number, limit: number, recycleItemId?: string, keyword?: string, customerIds?: string[]): Promise<RecycleCustomerAccountPage> {
|
||||
return await axios.post(`${ACCOUNT_URI}/customers`, undefined, {
|
||||
params: { storeId: getCurrentStoreId() || undefined, offset, limit, recycleItemId: recycleItemId || undefined, keyword: keyword || undefined, customerIds: customerIds?.length ? customerIds.join(",") : undefined }
|
||||
async function accountCustomers(index: number, size: number, recycleItemId?: string, keyword?: string, customerIds?: string[]): Promise<RecycleCustomerAccountPage> {
|
||||
return await axios.post(`${ACCOUNT_URI}/customers`, {
|
||||
storeId: getCurrentStoreId() || undefined, index, size,
|
||||
recycleItemId: recycleItemId || undefined, keyword: keyword || undefined,
|
||||
customerIds: customerIds?.length ? customerIds : undefined
|
||||
});
|
||||
}
|
||||
|
||||
@@ -130,11 +133,27 @@ async function accountItems(): Promise<RecycleItem[]> {
|
||||
return await axios.post(`${ACCOUNT_URI}/items`, undefined, { params: { storeId: getCurrentStoreId() || undefined } });
|
||||
}
|
||||
|
||||
/** 额度流水,服务端当前最多返回 100 条。 */
|
||||
async function accountLedger(customerId: string): Promise<RecycleLedger[]> {
|
||||
return await axios.post(`${ACCOUNT_URI}/ledger`, undefined, {
|
||||
params: { storeId: getCurrentStoreId() || undefined, customerId }
|
||||
});
|
||||
/** 分页查询回收物额度流水。 */
|
||||
async function ledgerList(page: {
|
||||
index: number; size: number; customerId?: string; recycleItemId?: string; keyword?: string;
|
||||
bizType?: string; beginAt?: number; endAt?: number;
|
||||
}): Promise<RecyclePageResult<RecycleLedger>> {
|
||||
return await axios.post(`${LEDGER_URI}/list`, { ...page, storeId: getCurrentStoreId() || undefined });
|
||||
}
|
||||
|
||||
/** 查询回收物额度流水详情。 */
|
||||
async function ledgerDetail(id: string): Promise<RecycleLedger> {
|
||||
return await axios.post(`${LEDGER_URI}/detail`, undefined, { params: { id } });
|
||||
}
|
||||
|
||||
/** 查询回收物支付详情。 */
|
||||
async function paymentDetail(id: string): Promise<RecyclePayment> {
|
||||
return await axios.post(`${PAYMENT_URI}/detail`, undefined, { params: { id } });
|
||||
}
|
||||
|
||||
/** 按客户分页查询额度流水。 */
|
||||
async function accountLedger(customerId: string, index: number, size: number): Promise<RecyclePageResult<RecycleLedger>> {
|
||||
return await ledgerList({ customerId, index, size });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -143,7 +162,7 @@ async function accountLedger(customerId: string): Promise<RecycleLedger[]> {
|
||||
* 减少不能超过可用额度;调整只动账面,不代表门店收到实物。
|
||||
*/
|
||||
async function accountAdjust(request: RecycleAccountAdjustRequest): Promise<void> {
|
||||
await axios.post(`${ACCOUNT_URI}/adjust`, withCurrentStoreId(request));
|
||||
await axios.post(`${LEDGER_URI}/adjust`, withCurrentStoreId(request));
|
||||
}
|
||||
|
||||
/** 某 SKU 的回收物产出配置。 */
|
||||
@@ -260,6 +279,9 @@ export default {
|
||||
accountCustomers,
|
||||
accountItems,
|
||||
accountLedger,
|
||||
ledgerList,
|
||||
ledgerDetail,
|
||||
paymentDetail,
|
||||
accountAdjust,
|
||||
yieldList,
|
||||
yieldProductList,
|
||||
|
||||
@@ -64,6 +64,39 @@ html.theme-dark body {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
// 消息提示避开顶部安全区和导航栏。
|
||||
.t-message {
|
||||
margin-top: calc(var(--tui-safe-top, 0px) + 48px);
|
||||
|
||||
&.message-enter-active {
|
||||
animation: message-slide-in .5s;
|
||||
}
|
||||
|
||||
&.message-leave-active {
|
||||
animation: message-slide-out .45s;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes message-slide-in {
|
||||
from {
|
||||
transform: translateY(calc(-100% - var(--tui-safe-top, 0px) - 58px));
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes message-slide-out {
|
||||
from {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateY(calc(-100% - var(--tui-safe-top, 0px) - 58px));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面骨架(tui-page-layout / tui-page-content / tui-navbar / tui-tabbar)由
|
||||
* timi-tdesign-mobile 的 page-layout.less 提供,这里只保留业务侧约定。
|
||||
@@ -78,7 +111,7 @@ html.theme-dark body {
|
||||
--td-search-square-radius: 1rem;
|
||||
|
||||
top: -1rem;
|
||||
margin: -1rem 0 1rem 0;
|
||||
margin: -1rem 0 0 0;
|
||||
padding: 1rem 1rem 0 1rem;
|
||||
z-index: 10;
|
||||
position: sticky;
|
||||
@@ -123,8 +156,11 @@ html.theme-dark body {
|
||||
-webkit-overflow-scrolling: touch;
|
||||
|
||||
.t-pull-down-refresh__track {
|
||||
gap: 1rem;
|
||||
height: auto;
|
||||
display: flex;
|
||||
min-height: 100%;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
&.has-dropdown-menu-navbar {
|
||||
|
||||
@@ -40,11 +40,16 @@
|
||||
:key="item.id"
|
||||
:title="getRecordEventName(item)"
|
||||
:description="getRecordCustomerName(item)"
|
||||
:note="`${formatRecordTime(item.registeredAt)}`"
|
||||
:note="formatRecordTime(item.registeredAt)"
|
||||
arrow
|
||||
hover
|
||||
@click="toRecordDetail(item)"
|
||||
/>
|
||||
>
|
||||
<template #left-icon>
|
||||
<t-image v-if="getRecordPhotoURL(item)" :src="getRecordPhotoURL(item)" :alt="getRecordCustomerName(item)" fit="cover" class="avatar" />
|
||||
<div v-else class="avatar fallback" v-text="getRecordCustomerName(item).slice(0, 1)" />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<center-tips v-else>该日暂无登记事件记录</center-tips>
|
||||
</div>
|
||||
@@ -72,6 +77,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import StoreAPI from "@/api/StoreAPI";
|
||||
import EventRecordAPI from "@/api/EventRecordAPI";
|
||||
import EventSelector from "@/components/EventSelector.vue";
|
||||
import MonthCalendar from "@/components/monthCalendar/MonthCalendar.vue";
|
||||
import { buildMonthCalendarDays, type MonthCalendarDay } from "@/components/monthCalendar/monthCalendar";
|
||||
@@ -79,6 +85,7 @@ import type {EventItem} from "@/types/EventItem";
|
||||
import type {EventRecord} from "@/types/EventRecord";
|
||||
import type {StoreBusinessDay} from "@/types/Store";
|
||||
import {getCurrentStoreId} from "@/utils/store";
|
||||
import {getCustomerPhotoURL} from "@/utils/customer";
|
||||
import {Time} from "timi-web";
|
||||
|
||||
interface CalendarDay extends MonthCalendarDay {
|
||||
@@ -126,6 +133,7 @@ const selectedDayTitle = ref("");
|
||||
const selectedDayRecords = ref<EventRecord[]>([]);
|
||||
const businessDayList = ref<StoreBusinessDay[]>([]);
|
||||
let businessDayRequestId = 0;
|
||||
let dayRecordRequestId = 0;
|
||||
|
||||
const selectedEventIdListProxy = computed({
|
||||
get: () => props.selectedEventIdList,
|
||||
@@ -199,7 +207,7 @@ function getDayRecords(dateText: string): EventRecord[] {
|
||||
return filteredRecords.value.filter(item => getRecordDateText(item) === dateText);
|
||||
}
|
||||
|
||||
function openDayRecords(day: MonthCalendarDay): void {
|
||||
async function openDayRecords(day: MonthCalendarDay): Promise<void> {
|
||||
const records = getDayRecords(day.dateText);
|
||||
if (!records.length) {
|
||||
return;
|
||||
@@ -208,6 +216,31 @@ function openDayRecords(day: MonthCalendarDay): void {
|
||||
selectedDayTitle.value = `${day.dateText} 登记事件记录`;
|
||||
selectedDayRecords.value = [...records].sort((left, right) => (right.registeredAt || 0) - (left.registeredAt || 0));
|
||||
dayRecordVisible.value = true;
|
||||
const requestId = ++dayRecordRequestId;
|
||||
const [year, month, date] = day.dateText.split("-").map(Number);
|
||||
const begin = new Date(year, month - 1, date);
|
||||
const end = new Date(year, month - 1, date, 23, 59, 59, 999);
|
||||
const customerIds = [...new Set(records.map(item => item.customerId).filter((id): id is string => Boolean(id)))];
|
||||
const eventIds = [...new Set(records.map(item => item.eventId).filter((id): id is string => Boolean(id)))];
|
||||
try {
|
||||
const result = await EventRecordAPI.list({
|
||||
index: 0,
|
||||
size: records.length,
|
||||
storeId: resolvedStoreId.value,
|
||||
customerId: customerIds.length === 1 ? customerIds[0] : undefined,
|
||||
eventIdList: eventIds,
|
||||
beginAt: Time.toTimestamp(begin),
|
||||
endAt: Time.toTimestamp(end)
|
||||
});
|
||||
if (requestId !== dayRecordRequestId) return;
|
||||
const customers = new Map((result.list || []).map(item => [item.id, item.customer]));
|
||||
selectedDayRecords.value = selectedDayRecords.value.map(item => ({
|
||||
...item,
|
||||
customer: customers.get(item.id) || item.customer
|
||||
}));
|
||||
} catch {
|
||||
// 记录资料不可用时保留姓名占位。
|
||||
}
|
||||
}
|
||||
|
||||
function openRecordList(): void {
|
||||
@@ -243,6 +276,10 @@ function getRecordCustomerName(record: EventRecord): string {
|
||||
return record.customer?.name || props.customerName || record.customerId || "未知客户";
|
||||
}
|
||||
|
||||
function getRecordPhotoURL(record: EventRecord): string {
|
||||
return getCustomerPhotoURL(record.customer, 64);
|
||||
}
|
||||
|
||||
function formatRecordTime(value?: number): string {
|
||||
if (!value) {
|
||||
return "-";
|
||||
@@ -252,7 +289,7 @@ function formatRecordTime(value?: number): string {
|
||||
if (!date) {
|
||||
return "-";
|
||||
}
|
||||
return Time.toDateTime(date);
|
||||
return Time.toTime(date);
|
||||
}
|
||||
|
||||
function getRecordDateText(record: EventRecord): string {
|
||||
@@ -341,6 +378,18 @@ function toDateValue(date: Date): number {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
}
|
||||
|
||||
.fallback {
|
||||
display: flex;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-popup {
|
||||
|
||||
@@ -53,7 +53,8 @@ import type {
|
||||
import type { PhotoItem } from "@/types/Photo.ts";
|
||||
import { getAttachmentReadURL } from "@/utils/attachment.ts";
|
||||
import { Message } from "@/utils/message.ts";
|
||||
import { saveCapturedFilesFromInput } from "@/utils/twaBridge";
|
||||
import { saveToAlbum } from "@/utils/mediaSaver";
|
||||
import { useSettingStore } from "@/store/settingStore";
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false
|
||||
@@ -77,6 +78,8 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
required: false
|
||||
});
|
||||
|
||||
const settingStore = useSettingStore();
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:items": [items: PhotoItem[]];
|
||||
select: [selection: AttachmentSelectorSelection];
|
||||
@@ -89,7 +92,13 @@ const isBusy = computed(() => props.busy || isUploading.value);
|
||||
const attachmentItems = computed(() => props.items.map(toAttachmentSelectorItem));
|
||||
|
||||
async function handleSelect(selection: AttachmentSelectorSelection): Promise<void> {
|
||||
saveCapturedFilesFromInput(selection.input, selection.files);
|
||||
// 直接拍摄的媒体额外存一份到系统相册,可在「应用设置」里关掉;失败不阻塞上传
|
||||
if (settingStore.albumSave && selection.input.capture && selection.files.length) {
|
||||
const mediaType: "image" | "video" = selection.input.accept.toLowerCase().includes("video") ? "video" : "image";
|
||||
for (const file of selection.files) {
|
||||
void saveToAlbum(file, mediaType).catch(() => Message.warning("保存到系统相册失败"));
|
||||
}
|
||||
}
|
||||
if (!props.upload) {
|
||||
emit("select", selection);
|
||||
return;
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
v-model="tabVal"
|
||||
class="diselect"
|
||||
:items="navList"
|
||||
logo-text="糕"
|
||||
tab-bar-float
|
||||
:hide-nav="!tabBarStore.isShowing"
|
||||
@change="onChangeTab"
|
||||
@rail-click="onRailClick"
|
||||
>
|
||||
<template #logo>
|
||||
<logo class="brand-icon" />
|
||||
</template>
|
||||
<template #rail-extra>
|
||||
<t-button
|
||||
class="ai-entry"
|
||||
@@ -42,6 +44,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { AppShell, PageTransition, useLayout } from "timi-tdesign-mobile";
|
||||
import Logo from "@/pages/user/component/Logo.vue";
|
||||
import { useGlobalUIStore } from "@/store/globalUI";
|
||||
import { useTabBarStore } from "@/store/tabBarStore";
|
||||
import { gaoRoleCodes, permissionCodes } from "@/utils/permission";
|
||||
@@ -214,6 +217,13 @@ const pageClass = computed(() => ({
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.brand-icon {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: #fff;
|
||||
border-radius: .5rem;
|
||||
}
|
||||
|
||||
.ai-entry {
|
||||
--td-button-border-radius: var(--tui-rail-item-radius, .75rem);
|
||||
|
||||
@@ -241,3 +251,6 @@ const pageClass = computed(() => ({
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import { VCan, VRole } from "timi-web-api/utils/directives/Access";
|
||||
import type { ApiResponse } from "timi-web-api";
|
||||
import { Message } from "@/utils/message";
|
||||
import { runAutoUpdate } from "@/composables/useAppUpdate";
|
||||
import { initializeTwaBridge } from "@/utils/twaBridge";
|
||||
import { VEntranceTransition } from "timi-tdesign-mobile";
|
||||
import timiWebStyle from "timi-web/src/assets/style/timi-web.less?inline";
|
||||
import tdesignCustomStyle from "timi-tdesign-mobile/src/assets/style/tdesign-custom.less?inline";
|
||||
@@ -29,8 +28,6 @@ export const pinia = createPinia();
|
||||
const apiBaseURL = import.meta.env.VITE_API_BASE_URL as string | undefined;
|
||||
const libraryOverrideStyleId = "library-override-style";
|
||||
|
||||
initializeTwaBridge();
|
||||
|
||||
function mountLibraryOverrideStyle(): void {
|
||||
const oldStyle = document.getElementById(libraryOverrideStyleId);
|
||||
oldStyle?.remove();
|
||||
|
||||
@@ -1,58 +1,105 @@
|
||||
<template>
|
||||
<div class="tui-page-layout tui-navbar customer-recycle-list">
|
||||
<t-navbar fixed :z-index="20" title="客户回收物" left-arrow @left-click="$router.back()" />
|
||||
<main v-can="permissionCodes.recycleAccount.read" class="tui-page-content scroll column">
|
||||
<t-pull-down-refresh v-model="refreshing" class="pull-refresh" :refresh-timeout="30000" @refresh="reload"
|
||||
@scrolltolower="loadMore">
|
||||
<t-navbar
|
||||
fixed
|
||||
:z-index="20"
|
||||
title="客户回收物"
|
||||
left-arrow
|
||||
@left-click="$router.back()"
|
||||
/>
|
||||
<master-detail-page
|
||||
v-can="permissionCodes.recycleAccount.read"
|
||||
class="list"
|
||||
:split="isWide"
|
||||
:selected="!!selectedCustomerId"
|
||||
:direction="paneDirection"
|
||||
>
|
||||
<template #master>
|
||||
<t-pull-down-refresh
|
||||
v-model="refreshing"
|
||||
class="pull-refresh"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="reload"
|
||||
@scrolltolower="loadMore"
|
||||
>
|
||||
<div class="filters glass">
|
||||
<t-input v-model.trim="keyword" type="search" borderless clearable placeholder="搜索客户姓名、拼音、编码">
|
||||
<template #suffix-icon>
|
||||
<t-button size="extra-small" theme="primary" variant="outline" :content="customerIds.length ? `已选 ${customerIds.length} 人` : '选择客户'" @click.stop="customerVisible = true" />
|
||||
<t-button
|
||||
size="extra-small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
:content="customerIds.length ? `已选 ${customerIds.length} 人` : '选择客户'"
|
||||
@click.stop="customerVisible = true"
|
||||
/>
|
||||
</template>
|
||||
</t-input>
|
||||
<t-dropdown-menu ref="filterMenuRef" class="menus">
|
||||
<t-dropdown-item :label="selectedName" :options="[]" @open="openItemPicker" />
|
||||
</t-dropdown-menu>
|
||||
</div>
|
||||
<t-cell-group theme="card">
|
||||
<t-cell title="汇总">
|
||||
<template v-if="selectedId" #note>
|
||||
<t-button size="extra-small" variant="outline" content="清除" @click="clearItem" />
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="tags">
|
||||
<t-tag v-for="item in displayedTotals" :key="item.recycleItemId" theme="primary"
|
||||
variant="light"
|
||||
:content="accountText(item)" />
|
||||
<span v-if="!displayedTotals.length" v-text="loading ? '正在加载' : '暂无回收物'" />
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="items.length" theme="card" class="fix-last-cell-line">
|
||||
<customer-cell v-for="row in items" :key="row.customer.id" :customer="row.customer" arrow hover
|
||||
@click="openCustomer(row.customer)">
|
||||
<template #description>
|
||||
<div class="tags">
|
||||
<t-tag v-for="account in row.accounts" :key="account.recycleItemId" theme="primary"
|
||||
variant="light"
|
||||
:content="accountText(account)" />
|
||||
</div>
|
||||
</template>
|
||||
</customer-cell>
|
||||
</t-cell-group>
|
||||
<center-tips v-else :content="loading ? '正在加载客户回收物' : '暂无客户回收物'" />
|
||||
<center-tips v-if="items.length"
|
||||
:content="loading ? '正在加载' : noMore ? `共 ${total} 位客户` : '上拉加载更多'" />
|
||||
<div class="list-wrap">
|
||||
<t-cell-group theme="card">
|
||||
<t-cell title="汇总">
|
||||
<template #note>
|
||||
<t-button v-if="selectedId" size="extra-small" variant="outline" content="清除" @click="clearItem" />
|
||||
<div class="tags">
|
||||
<t-tag
|
||||
v-for="item in displayedTotals" :key="item.recycleItemId" theme="primary"
|
||||
variant="light"
|
||||
:content="accountText(item)"
|
||||
/>
|
||||
<span v-if="!displayedTotals.length" v-text="loading ? '正在加载' : '暂无回收物'" />
|
||||
</div>
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="items.length" theme="card" class="fix-last-cell-line">
|
||||
<customer-cell
|
||||
v-for="row in items"
|
||||
:key="row.customer.id"
|
||||
:customer="row.customer"
|
||||
arrow
|
||||
hover
|
||||
@click="openCustomer(row.customer)"
|
||||
>
|
||||
<template #description>
|
||||
<div class="tags">
|
||||
<t-tag
|
||||
v-for="account in row.accounts"
|
||||
:key="account.recycleItemId" theme="primary"
|
||||
size="small"
|
||||
variant="light"
|
||||
:content="accountText(account)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</customer-cell>
|
||||
</t-cell-group>
|
||||
<center-tips
|
||||
v-else
|
||||
:content="loading ? '正在加载客户回收物' : '暂无客户回收物'"
|
||||
/>
|
||||
<center-tips
|
||||
v-if="items.length"
|
||||
:content="loading ? '正在加载' : noMore ? `共 ${total} 位客户` : '上拉加载更多'"
|
||||
/>
|
||||
</div>
|
||||
</t-pull-down-refresh>
|
||||
</main>
|
||||
</template>
|
||||
<template #detail>
|
||||
<recycle-account-page :key="selectedCustomerId" :initial-customer-id="selectedCustomerId" />
|
||||
</template>
|
||||
</master-detail-page>
|
||||
<customer-selector v-model="customerIds" v-model:visible="customerVisible" :initial-keyword="keyword" selection-mode="multiple" />
|
||||
<recycle-item-picker-popup v-model:visible="filterVisible" :selected-id="selectedId" account-items @select="selectItem" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
|
||||
import RecycleAPI from "@/api/RecycleAPI";
|
||||
import RecycleAccountPage from "@/pages/recycle/RecycleAccount.vue";
|
||||
import RecycleItemPickerPopup from "@/pages/recycle/components/RecycleItemPickerPopup.vue";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
@@ -63,7 +110,11 @@ import { permissionCodes } from "@/utils/permission";
|
||||
import { getRecycleQuantityText } from "@/utils/recycle";
|
||||
|
||||
defineOptions({ name: "CustomerRecycleList" });
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const { selectedId: selectedCustomerId, isWide, paneDirection, openDetail } = useMasterDetailPane({
|
||||
path: "/management/customer-recycle-accounts",
|
||||
detail: id => `/management/recycle-accounts?customerId=${encodeURIComponent(id)}&transitionDepth=${Number(route.meta.depth ?? 0) + 1}`
|
||||
});
|
||||
const items = ref<RecycleCustomerAccountPage["list"]>([]);
|
||||
const totals = ref<RecycleAccount[]>([]);
|
||||
const selectedId = ref("");
|
||||
@@ -79,6 +130,7 @@ const refreshing = ref(false);
|
||||
const noMore = ref(false);
|
||||
const total = ref(0);
|
||||
let version = 0;
|
||||
let pageIndex = 0;
|
||||
const selectedName = computed(() => selectedItem.value?.name || "全部回收物");
|
||||
const displayedTotals = computed(() => selectedId.value ? totals.value.filter(item => item.recycleItemId === selectedId.value) : totals.value);
|
||||
|
||||
@@ -89,15 +141,16 @@ function accountText(account: RecycleAccount): string {
|
||||
async function fetchPage(reset: boolean): Promise<void> {
|
||||
if (!reset && (loading.value || noMore.value)) return;
|
||||
const token = reset ? ++version : version;
|
||||
const offset = reset ? 0 : items.value.length;
|
||||
const index = reset ? 0 : pageIndex;
|
||||
if (reset) {
|
||||
items.value = [];
|
||||
noMore.value = false;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await RecycleAPI.accountCustomers(offset, 20, selectedId.value, keyword.value, customerIds.value);
|
||||
const result = await RecycleAPI.accountCustomers(index, 20, selectedId.value, keyword.value, customerIds.value);
|
||||
if (token !== version) return;
|
||||
pageIndex = index + 1;
|
||||
items.value = reset ? result.list : [...items.value, ...result.list];
|
||||
totals.value = result.totals;
|
||||
total.value = result.total;
|
||||
@@ -159,8 +212,8 @@ onUnmounted(() => {
|
||||
if (searchTimer) clearTimeout(searchTimer);
|
||||
});
|
||||
|
||||
async function openCustomer(customer: Customer): Promise<void> {
|
||||
if (customer.id) await router.push({ name: "RecycleAccount", query: { customerId: customer.id } });
|
||||
function openCustomer(customer: Customer): void {
|
||||
if (customer.id) openDetail(customer.id);
|
||||
}
|
||||
|
||||
let wasDeactivated = false;
|
||||
@@ -175,11 +228,18 @@ onActivated(async () => {
|
||||
|
||||
<style scoped lang="less">
|
||||
.customer-recycle-list {
|
||||
.tags {
|
||||
gap: .375rem;
|
||||
|
||||
.list-wrap {
|
||||
gap: 1rem;
|
||||
display: flex;
|
||||
padding: .25rem 0;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
|
||||
.tags {
|
||||
gap: .375rem;
|
||||
display: flex;
|
||||
padding: .25rem 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -57,6 +57,9 @@ const props = withDefaults(defineProps<{
|
||||
}>(), {
|
||||
notifyId: ""
|
||||
});
|
||||
const emit = defineEmits<{
|
||||
read: [];
|
||||
}>();
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -171,6 +174,7 @@ async function markRead(item: NotifyDetail, requestToken: number): Promise<void>
|
||||
}
|
||||
try {
|
||||
await NotifyAPI.markInternalRead(item.id);
|
||||
emit("read");
|
||||
if (requestToken === loadToken && detail.value) {
|
||||
detail.value = {
|
||||
...detail.value,
|
||||
|
||||
@@ -94,6 +94,7 @@
|
||||
<user-notify-detail
|
||||
:key="`detail-${selectedId}`"
|
||||
:notify-id="selectedId"
|
||||
@read="handleDetailRead"
|
||||
/>
|
||||
</template>
|
||||
</master-detail-page>
|
||||
@@ -233,6 +234,16 @@ async function refresh(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDetailRead(): Promise<void> {
|
||||
try {
|
||||
await reloadList();
|
||||
await loadUnreadCount();
|
||||
} catch (error) {
|
||||
console.warn("已读通知刷新失败", error);
|
||||
Message.error("通知列表刷新失败");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 操作 ----------
|
||||
|
||||
const isMarkingAllRead = ref(false);
|
||||
|
||||
@@ -169,11 +169,16 @@ const props = withDefaults(defineProps<{
|
||||
configId: ""
|
||||
});
|
||||
|
||||
const emit = defineEmits<{ saved: [] }>();
|
||||
|
||||
const route = useRoute();
|
||||
/** 内联渲染时 id 来自 prop,整页渲染时来自路由参数 */
|
||||
const currentId = computed(() => props.configId || String(route.params.id || ""));
|
||||
|
||||
const routeNavBarTitle = computed(() => {
|
||||
if (pane && !currentId.value) {
|
||||
return "新增套餐配置";
|
||||
}
|
||||
// 内联时路由停在列表页,标题只能看当前是新增还是编辑
|
||||
if (props.configId) {
|
||||
return "编辑套餐配置";
|
||||
@@ -452,6 +457,7 @@ async function save(): Promise<void> {
|
||||
const id = await PackageAPI.configCreate(payload);
|
||||
Message.success("套餐配置已创建");
|
||||
if (pane) {
|
||||
emit("saved");
|
||||
pane.close(true);
|
||||
return;
|
||||
}
|
||||
@@ -461,6 +467,7 @@ async function save(): Promise<void> {
|
||||
await PackageAPI.configUpdate(payload);
|
||||
Message.success("套餐配置已保存");
|
||||
if (pane) {
|
||||
emit("saved");
|
||||
pane.close(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -103,7 +103,8 @@
|
||||
</t-pull-down-refresh>
|
||||
</template>
|
||||
<template #detail>
|
||||
<package-config-edit v-if="editing" :key="`edit-${selectedId}`" :config-id="selectedId" />
|
||||
<package-config-edit v-if="selectedId === createPaneId" :key="createPaneId" @saved="reload" />
|
||||
<package-config-edit v-else-if="editing" :key="`edit-${selectedId}`" :config-id="selectedId" @saved="reload" />
|
||||
<package-config-detail
|
||||
v-else
|
||||
:key="`detail-${selectedId}-${detailVersion}`"
|
||||
@@ -137,10 +138,11 @@ const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
|
||||
// 选中项、编辑态、切换方向、关闭逻辑、转屏、query 同步都在这里
|
||||
const createPaneId = "__create__";
|
||||
const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } =
|
||||
useMasterDetailPane({
|
||||
path: "/product/package-configs",
|
||||
detail: id => `/product/package-configs/${id}`,
|
||||
detail: id => id === createPaneId ? "/product/package-configs/create" : `/product/package-configs/${id}`,
|
||||
edit: id => `/product/package-configs/${id}/edit`
|
||||
});
|
||||
|
||||
@@ -216,6 +218,10 @@ watch(keyword, () => {
|
||||
});
|
||||
|
||||
async function toCreate(): Promise<void> {
|
||||
if (isWide.value && userStore.hasPermissions(permissionCodes.packageConfig.read)) {
|
||||
openDetail(createPaneId);
|
||||
return;
|
||||
}
|
||||
await router.push("/product/package-configs/create");
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
:z-index="20"
|
||||
:title="routeNavBarTitle"
|
||||
left-arrow
|
||||
@left-click="$router.back()"
|
||||
@left-click="exit"
|
||||
>
|
||||
<template #right>
|
||||
<t-button
|
||||
@@ -335,7 +335,7 @@
|
||||
import DateTimeNowPicker from "@/components/DateTimeNowPicker.vue";
|
||||
import { Time } from "timi-web";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import { BottomPopup } from "timi-tdesign-mobile";
|
||||
import { BottomPopup, usePane } from "timi-tdesign-mobile";
|
||||
import { DialogPlugin } from "tdesign-mobile-vue";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import PackageAPI from "@/api/PackageAPI";
|
||||
@@ -381,9 +381,13 @@ defineOptions({
|
||||
name: "PackagePurchase"
|
||||
});
|
||||
|
||||
const props = defineProps<{ createOrder?: boolean }>();
|
||||
const emit = defineEmits<{ created: [orderId: string] }>();
|
||||
const pane = usePane();
|
||||
const route = useRoute();
|
||||
|
||||
const routeNavBarTitle = computed(() => {
|
||||
if (props.createOrder) return "创建客户套餐";
|
||||
switch (route.name) {
|
||||
case "PackagePurchase":
|
||||
return "购买套餐";
|
||||
@@ -394,13 +398,20 @@ const routeNavBarTitle = computed(() => {
|
||||
}
|
||||
});
|
||||
const router = useRouter();
|
||||
function exit(): void {
|
||||
if (pane) {
|
||||
pane.close();
|
||||
return;
|
||||
}
|
||||
void router.back();
|
||||
}
|
||||
const settingStore = useSettingStore();
|
||||
const userStore = useUserStore();
|
||||
|
||||
// ---------- 套餐配置 ----------
|
||||
|
||||
const configId = computed(() => String(route.params.id || ""));
|
||||
const isCustomerPackageCreate = computed(() => route.name === "CustomerPackageCreate");
|
||||
const configId = computed(() => props.createOrder ? "" : String(route.params.id || ""));
|
||||
const isCustomerPackageCreate = computed(() => !!props.createOrder || route.name === "CustomerPackageCreate");
|
||||
const config = ref<GaoPackageConfig>();
|
||||
const configList = ref<GaoPackageConfig[]>([]);
|
||||
const configSelectorVisible = ref(false);
|
||||
@@ -914,6 +925,10 @@ async function purchasePackage(): Promise<void> {
|
||||
emitListDataChanged(listDataEventKeys.productStockChanged);
|
||||
await settingStore.playRegisterSuccessSound();
|
||||
Message.success(fulfillAll.value ? "套餐、收款及履约已完成" : paymentVerified.value ? "套餐及已核销收款已完成" : receiveFullPayment.value ? "套餐及全额收款已完成" : "套餐购买已提交");
|
||||
if (pane && props.createOrder) {
|
||||
emit("created", result.salesOrderId);
|
||||
return;
|
||||
}
|
||||
await router.replace({
|
||||
name: "SalesOrderDetail",
|
||||
params: { id: result.salesOrderId },
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
:z-index="20"
|
||||
title="积分流水详情"
|
||||
left-arrow
|
||||
@left-click="$router.back()"
|
||||
@left-click="goBack"
|
||||
/>
|
||||
<main class="tui-page-content scroll column">
|
||||
<div v-if="customer" v-can="permissionCodes.point.ledgerRead" class="point-ledger-detail">
|
||||
@@ -83,7 +83,7 @@
|
||||
<center-tips v-else :content="getRuleEmptyText()" />
|
||||
</t-cell-group>
|
||||
</template>
|
||||
<t-empty v-else :description="isLoading ? '正在加载积分流水' : '积分流水快照不存在,请从积分流水列表进入'" />
|
||||
<t-empty v-else :description="isLoading ? '正在加载积分流水' : '积分流水不存在或无权查看'" />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
@@ -92,11 +92,13 @@
|
||||
<script setup lang="ts">
|
||||
import { TimeLabel, Text } from "timi-web";
|
||||
import { useUserStore } from "timi-web-api";
|
||||
import { useExpandToMaster, usePane } from "timi-tdesign-mobile";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import EventAPI from "@/api/EventAPI";
|
||||
import EventRecordAPI from "@/api/EventRecordAPI";
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
import CustomerProfileCard from "@/components/CustomerProfileCard.vue";
|
||||
import { buildLedgerSubPane } from "@/pages/point/component/ledgerPane";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { EventItem } from "@/types/EventItem";
|
||||
import type { EventRecord } from "@/types/EventRecord";
|
||||
@@ -109,10 +111,48 @@ defineOptions({
|
||||
name: "PointLedgerDetail"
|
||||
});
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
/** 指定流水 ID 时忽略路由参数,用于平板主从分栏的内联渲染。 */
|
||||
ledgerId?: string;
|
||||
}>(), {
|
||||
ledgerId: ""
|
||||
});
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
|
||||
function resolveId(): string {
|
||||
return props.ledgerId || String(route.params.id || "");
|
||||
}
|
||||
|
||||
// 竖屏整页进来后转成横屏:回到列表页并恢复右栏选中,而不是继续停在整页详情
|
||||
useExpandToMaster({
|
||||
path: "/management/points/ledger",
|
||||
id: () => resolveId()
|
||||
});
|
||||
/** 非空说明当前被内联在主从分栏的右栏里 */
|
||||
const pane = usePane();
|
||||
|
||||
/**
|
||||
* 尝试在右栏压入一层子页(分栏的第三层)。
|
||||
*
|
||||
* 接不住时有三种情况:整页打开详情、窄屏、宿主列表没声明子页槽,
|
||||
* 此时返回 false,调用方退回整页跳转。
|
||||
*/
|
||||
function openSub(view: string): boolean {
|
||||
return pane?.openSub(view) ?? false;
|
||||
}
|
||||
|
||||
function goBack(): void {
|
||||
if (pane) {
|
||||
pane.close();
|
||||
return;
|
||||
}
|
||||
|
||||
void router.back();
|
||||
}
|
||||
|
||||
// ---------- 权限 ----------
|
||||
|
||||
const canReadCustomer = computed(() => userStore.hasPermissions(permissionCodes.customer.read));
|
||||
@@ -139,32 +179,6 @@ function isDeletedEventRevokeLedger(value?: PointLedger): boolean {
|
||||
return value?.changeType === "REVOKE" && value?.triggerSourceType === "EVENT_RECORD" && !value.triggerSourceId;
|
||||
}
|
||||
|
||||
function getQueryText(key: string): string {
|
||||
const value = route.query[key];
|
||||
return Array.isArray(value) ? String(value[0] || "") : String(value || "");
|
||||
}
|
||||
|
||||
function parseLedgerSnapshot(): PointLedger | undefined {
|
||||
const snapshotText = getQueryText("snapshot");
|
||||
if (!snapshotText) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const snapshot = JSON.parse(snapshotText) as PointLedger;
|
||||
if (!snapshot || typeof snapshot !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
...snapshot,
|
||||
id: String(route.params.id || snapshot.id || "")
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn("积分流水快照解析失败", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOptional<T>(loader: () => Promise<T>, message: string): Promise<T | undefined> {
|
||||
try {
|
||||
return await loader();
|
||||
@@ -175,17 +189,24 @@ async function loadOptional<T>(loader: () => Promise<T>, message: string): Promi
|
||||
}
|
||||
|
||||
async function loadPageData(): Promise<void> {
|
||||
ledger.value = parseLedgerSnapshot();
|
||||
ledger.value = undefined;
|
||||
customer.value = undefined;
|
||||
triggerEvent.value = undefined;
|
||||
eventRecord.value = undefined;
|
||||
hitRule.value = undefined;
|
||||
if (!ledger.value) {
|
||||
const id = resolveId();
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading.value = true;
|
||||
try {
|
||||
// 流水只追加不修改,缺字段的旧链接一律以服务端这条为准
|
||||
ledger.value = await PointAPI.ledgerDetail(id);
|
||||
if (!ledger.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ledger.value.triggerSourceType === "EVENT_RECORD" && ledger.value.triggerSourceId && canReadEventRecord.value && !isDeletedEventRevoke.value) {
|
||||
eventRecord.value = await loadOptional(() => EventRecordAPI.detail(ledger.value!.triggerSourceId!), "积分流水关联事件记录加载失败");
|
||||
}
|
||||
@@ -200,14 +221,20 @@ async function loadPageData(): Promise<void> {
|
||||
const ruleResult = ledger.value.ruleId && canReadRule.value
|
||||
? loadOptional(() => PointAPI.ruleDetail(ledger.value!.ruleId!), "积分流水命中规则加载失败")
|
||||
: Promise.resolve(undefined);
|
||||
const customerResult = !eventRecord.value?.customer && ledger.value.customerId && canReadCustomer.value
|
||||
? loadOptional(() => CustomerAPI.detail(ledger.value!.customerId!), "积分流水客户加载失败")
|
||||
: Promise.resolve(undefined);
|
||||
// 详情接口已经把客户资料带回来了,只有缺失时才单独补一次
|
||||
const customerResult = ledger.value.customer
|
||||
? Promise.resolve(ledger.value.customer)
|
||||
: !eventRecord.value?.customer && ledger.value.customerId && canReadCustomer.value
|
||||
? loadOptional(() => CustomerAPI.detail(ledger.value!.customerId!), "积分流水客户加载失败")
|
||||
: Promise.resolve(undefined);
|
||||
|
||||
[triggerEvent.value, hitRule.value, customer.value] = await Promise.all([eventResult, ruleResult, customerResult]);
|
||||
if (eventRecord.value?.customer) {
|
||||
customer.value = eventRecord.value.customer;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("积分流水加载失败", error);
|
||||
ledger.value = undefined;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
@@ -312,43 +339,54 @@ function getRuleEmptyText(): string {
|
||||
// ---------- 导航 ----------
|
||||
|
||||
async function toCustomerDetail(): Promise<void> {
|
||||
if (customer.value?.id) {
|
||||
await router.push(`/management/customers/${customer.value.id}`);
|
||||
const id = customer.value?.id;
|
||||
if (!id || openSub(buildLedgerSubPane("customer", id))) {
|
||||
return;
|
||||
}
|
||||
await router.push(`/management/customers/${id}`);
|
||||
}
|
||||
|
||||
async function toPointAccount(): Promise<void> {
|
||||
if (!canReadPointAccount.value || !ledger.value?.accountId) {
|
||||
const accountId = ledger.value?.accountId;
|
||||
if (!canReadPointAccount.value || !accountId) {
|
||||
return;
|
||||
}
|
||||
if (openSub(buildLedgerSubPane("account", accountId, ledger.value?.storeId || ""))) {
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "PointAccountDetail",
|
||||
params: { id: ledger.value.accountId },
|
||||
params: { id: accountId },
|
||||
query: {
|
||||
storeId: ledger.value.storeId || "",
|
||||
storeId: ledger.value?.storeId || "",
|
||||
transitionDepth: String(Number(route.meta.depth ?? 0) + 1)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function toEventDetail(): Promise<void> {
|
||||
if (!canReadEvent.value || !triggerEvent.value?.id) {
|
||||
const id = triggerEvent.value?.id;
|
||||
if (!canReadEvent.value || !id) {
|
||||
return;
|
||||
}
|
||||
if (openSub(buildLedgerSubPane("event", id))) {
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "EventDetail",
|
||||
params: { id: triggerEvent.value.id },
|
||||
params: { id },
|
||||
query: { transitionDepth: String(Number(route.meta.depth ?? 0) + 1) }
|
||||
});
|
||||
}
|
||||
|
||||
async function toEventRecordDetail(): Promise<void> {
|
||||
if (!eventRecord.value?.id) {
|
||||
const id = eventRecord.value?.id;
|
||||
if (!id || openSub(buildLedgerSubPane("event-record", id))) {
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "EventRecordDetail",
|
||||
params: { id: eventRecord.value.id },
|
||||
params: { id },
|
||||
query: {
|
||||
transitionDepth: String(Number(route.meta.depth ?? 0) + 1),
|
||||
changeType: ledger.value?.changeType
|
||||
@@ -357,17 +395,30 @@ async function toEventRecordDetail(): Promise<void> {
|
||||
}
|
||||
|
||||
async function toPointRuleDetail(): Promise<void> {
|
||||
if (!canReadRule.value || !hitRule.value?.id) {
|
||||
const id = hitRule.value?.id;
|
||||
if (!canReadRule.value || !id) {
|
||||
return;
|
||||
}
|
||||
if (openSub(buildLedgerSubPane("rule", id))) {
|
||||
return;
|
||||
}
|
||||
await router.push({
|
||||
name: "PointRuleDetail",
|
||||
params: { id: hitRule.value.id },
|
||||
params: { id },
|
||||
query: { transitionDepth: String(Number(route.meta.depth ?? 0) + 1) }
|
||||
});
|
||||
}
|
||||
|
||||
watch(() => [route.params.id, route.query.snapshot], async () => {
|
||||
/**
|
||||
* 重载判据:两个来源拼成一个字符串再 watch。
|
||||
*
|
||||
* 不能直接 watch `[props.ledgerId, route.params.id]`:读 `route.params.id` 会依赖
|
||||
* 整个 `params` 对象,分栏里改个 query(进子页、返回)也会被连带触发,
|
||||
* `loadPageData` 一进来就把 ledger 置空重拉,看起来就是详情页自己刷新了一遍。
|
||||
*/
|
||||
const reloadKey = computed(() => `${props.ledgerId}|${String(route.params.id || "")}`);
|
||||
|
||||
watch(reloadKey, async () => {
|
||||
await loadPageData();
|
||||
}, { immediate: true });
|
||||
</script>
|
||||
|
||||
@@ -7,117 +7,136 @@
|
||||
left-arrow
|
||||
@left-click="$router.back()"
|
||||
/>
|
||||
<main v-can="permissionCodes.point.ledgerRead" class="tui-page-content scroll column list">
|
||||
<t-pull-down-refresh
|
||||
class="pull-refresh"
|
||||
v-model="isRefreshing"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="reload"
|
||||
@scrolltolower="load"
|
||||
>
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="customerKeyword"
|
||||
class="customer"
|
||||
type="search"
|
||||
borderless
|
||||
placeholder="输入客户编码或姓名"
|
||||
@clear="searchCustomer"
|
||||
@enter="searchCustomer"
|
||||
@input="searchCustomer"
|
||||
>
|
||||
<template #suffix-icon>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
content="选择客户"
|
||||
@click.stop="selectorVisible = true"
|
||||
/>
|
||||
</template>
|
||||
</t-input>
|
||||
<t-dropdown-menu class="menus">
|
||||
<t-dropdown-item
|
||||
v-model="changeTypeFilter"
|
||||
label="流水类型"
|
||||
:options="changeTypeOptions"
|
||||
@change="selectChangeType"
|
||||
/>
|
||||
<t-dropdown-item
|
||||
v-model="dateFilter"
|
||||
:label="dateFilterLabel"
|
||||
:options="dateFilterOptions"
|
||||
@change="selectDateFilter"
|
||||
/>
|
||||
</t-dropdown-menu>
|
||||
</div>
|
||||
<div class="list-wrap">
|
||||
<card-container v-if="customer" class="customer">
|
||||
<customer-profile-card :customer="customer" />
|
||||
</card-container>
|
||||
<t-cell-group class="summary" theme="card">
|
||||
<t-cell
|
||||
title="开始时间"
|
||||
:note="dateRange[0] || '-'"
|
||||
arrow
|
||||
@click="openStartDate"
|
||||
/>
|
||||
<t-cell
|
||||
title="结束时间"
|
||||
:note="dateRange[1] || '-'"
|
||||
arrow
|
||||
@click="openEndDate"
|
||||
/>
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="pageResult.list.length" class="list" theme="card">
|
||||
<t-cell
|
||||
v-entrance-transition="{ step: 30 }"
|
||||
v-for="item in pageResult.list"
|
||||
:key="item.id"
|
||||
class="item"
|
||||
:arrow="!!item.id"
|
||||
:hover="!!item.id"
|
||||
@click="toDetail(item)"
|
||||
<master-detail-page
|
||||
v-can="permissionCodes.point.ledgerRead"
|
||||
class="list"
|
||||
:split="isWide"
|
||||
:selected="!!selectedId"
|
||||
:direction="paneDirection"
|
||||
:sub="!!subView"
|
||||
>
|
||||
<template #master>
|
||||
<t-pull-down-refresh
|
||||
class="pull-refresh"
|
||||
v-model="isRefreshing"
|
||||
:refresh-timeout="30000"
|
||||
@refresh="reload"
|
||||
@scrolltolower="load"
|
||||
>
|
||||
<div class="filters glass">
|
||||
<t-input
|
||||
v-model="customerKeyword"
|
||||
class="customer"
|
||||
type="search"
|
||||
borderless
|
||||
placeholder="输入客户编码或姓名"
|
||||
@clear="searchCustomer"
|
||||
@enter="searchCustomer"
|
||||
@input="searchCustomer"
|
||||
>
|
||||
<template #leftIcon>
|
||||
<t-image
|
||||
v-if="getCustomerPhotoURL(item.customer!, 64)"
|
||||
:src="getCustomerPhotoURL(item.customer!, 64)"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
<template #suffix-icon>
|
||||
<t-button
|
||||
size="extra-small"
|
||||
theme="primary"
|
||||
variant="outline"
|
||||
content="选择客户"
|
||||
@click.stop="selectorVisible = true"
|
||||
/>
|
||||
<div v-else class="avatar fallback" v-text="(item.customer?.name || item.customer?.code || '客').slice(0, 1)" />
|
||||
</template>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<t-tag
|
||||
class="type-icon"
|
||||
:theme="item.pointDelta && 0 < item.pointDelta ? 'success' : 'danger'"
|
||||
:content="getLedgerShortType(item)"
|
||||
variant="outline"
|
||||
</t-input>
|
||||
<t-dropdown-menu class="menus">
|
||||
<t-dropdown-item
|
||||
v-model="changeTypeFilter"
|
||||
label="流水类型"
|
||||
:options="changeTypeOptions"
|
||||
@change="selectChangeType"
|
||||
/>
|
||||
<t-dropdown-item
|
||||
v-model="dateFilter"
|
||||
:label="dateFilterLabel"
|
||||
:options="dateFilterOptions"
|
||||
@change="selectDateFilter"
|
||||
/>
|
||||
</t-dropdown-menu>
|
||||
</div>
|
||||
<div class="list-wrap">
|
||||
<card-container v-if="customer" class="customer">
|
||||
<customer-profile-card :customer="customer" />
|
||||
</card-container>
|
||||
<t-cell-group class="summary" theme="card">
|
||||
<t-cell
|
||||
title="开始时间"
|
||||
:note="dateRange[0] || '-'"
|
||||
arrow
|
||||
@click="openStartDate"
|
||||
/>
|
||||
<t-cell
|
||||
title="结束时间"
|
||||
:note="dateRange[1] || '-'"
|
||||
arrow
|
||||
@click="openEndDate"
|
||||
/>
|
||||
</t-cell-group>
|
||||
<t-cell-group v-if="pageResult.list.length" class="list" theme="card">
|
||||
<t-cell
|
||||
v-entrance-transition="{ step: 30 }"
|
||||
v-for="item in pageResult.list"
|
||||
:key="item.id"
|
||||
class="item"
|
||||
:arrow="!!item.id"
|
||||
:hover="!!item.id"
|
||||
@click="toDetail(item)"
|
||||
>
|
||||
<template #leftIcon>
|
||||
<t-image
|
||||
v-if="getCustomerPhotoURL(item.customer!, 64)"
|
||||
:src="getCustomerPhotoURL(item.customer!, 64)"
|
||||
fit="cover"
|
||||
class="avatar"
|
||||
/>
|
||||
<div class="name" v-text="item.customer?.name" />
|
||||
</div>
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="description">
|
||||
<div>
|
||||
<span>时间:</span>
|
||||
<time-label :timestamp="item.occurredAt" underline />
|
||||
<div v-else class="avatar fallback" v-text="(item.customer?.name || item.customer?.code || '客').slice(0, 1)" />
|
||||
</template>
|
||||
<template #title>
|
||||
<div class="title">
|
||||
<t-tag
|
||||
class="type-icon"
|
||||
:theme="item.pointDelta && 0 < item.pointDelta ? 'success' : 'danger'"
|
||||
:content="getLedgerShortType(item)"
|
||||
variant="outline"
|
||||
/>
|
||||
<div class="name" v-text="item.customer?.name" />
|
||||
</div>
|
||||
<div v-text="`余额:${formatPointValue(item.balanceBefore)} → ${formatPointValue(item.balanceAfter)}`" />
|
||||
<div v-text="item.remark" />
|
||||
</div>
|
||||
</template>
|
||||
<template #note>
|
||||
<div class="delta keep-text" :class="getLedgerTheme(item)" v-text="getLedgerDelta(item)" />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<center-tips :content="loadStateText" />
|
||||
</div>
|
||||
</t-pull-down-refresh>
|
||||
</main>
|
||||
</template>
|
||||
<template #description>
|
||||
<div class="description">
|
||||
<div>
|
||||
<span>时间:</span>
|
||||
<time-label :timestamp="item.occurredAt" underline />
|
||||
</div>
|
||||
<div v-text="`余额:${formatPointValue(item.balanceBefore)} → ${formatPointValue(item.balanceAfter)}`" />
|
||||
<div v-text="item.remark" />
|
||||
</div>
|
||||
</template>
|
||||
<template #note>
|
||||
<div class="delta keep-text" :class="getLedgerTheme(item)" v-text="getLedgerDelta(item)" />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<center-tips :content="loadStateText" />
|
||||
</div>
|
||||
</t-pull-down-refresh>
|
||||
</template>
|
||||
<template #detail>
|
||||
<point-ledger-detail :key="`detail-${selectedId}`" :ledger-id="selectedId" />
|
||||
</template>
|
||||
<!--
|
||||
第三层:详情点进子页(客户 / 积分账户 / 事件 / 事件记录 / 积分规则)时,
|
||||
列表整列滑出、详情退到主栏,右栏换成那个子页。
|
||||
-->
|
||||
<template #sub>
|
||||
<ledger-sub-view :key="subView" :view="subView" />
|
||||
</template>
|
||||
</master-detail-page>
|
||||
<customer-selector
|
||||
v-model="selectedCustomerId"
|
||||
v-model:visible="selectorVisible"
|
||||
@@ -152,11 +171,15 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { DropdownValue } from "tdesign-mobile-vue";
|
||||
import { MasterDetailPage, useMasterDetailPane } from "timi-tdesign-mobile";
|
||||
import { TimeLabel, Toolkit } from "timi-web";
|
||||
import { type PageResult, useUserStore } from "timi-web-api";
|
||||
import CustomerAPI from "@/api/CustomerAPI";
|
||||
import PointAPI from "@/api/PointAPI";
|
||||
import CustomerSelector from "@/components/CustomerSelector.vue";
|
||||
import PointLedgerDetail from "@/pages/point/PointLedgerDetail.vue";
|
||||
import LedgerSubView from "@/pages/point/component/LedgerSubView.vue";
|
||||
import { getLedgerSubRoute, parseLedgerSubPane } from "@/pages/point/component/ledgerPane";
|
||||
import { useCurrentStoreStore } from "@/store/currentStoreStore";
|
||||
import type { Customer } from "@/types/Customer";
|
||||
import type { PointLedger, PointLedgerChangeType, PointLedgerPage } from "@/types/Point";
|
||||
@@ -172,10 +195,27 @@ defineOptions({
|
||||
});
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
const currentStoreStore = useCurrentStoreStore();
|
||||
|
||||
// ---------- 分栏导航 ----------
|
||||
|
||||
// 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里;积分流水没有内联编辑视图
|
||||
const { selectedId, subView, paneDirection, isWide, openDetail } = useMasterDetailPane({
|
||||
path: "/management/points/ledger",
|
||||
detail: detailRoute
|
||||
});
|
||||
|
||||
/**
|
||||
* 转屏变窄时右栏不再渲染,按右栏当前那一层落到整页路由。
|
||||
*
|
||||
* 子页落到各自模块的整页,详情落到流水自己的详情页。
|
||||
*/
|
||||
function detailRoute(id: string): string {
|
||||
const sub = parseLedgerSubPane(subView.value || "");
|
||||
return sub ? getLedgerSubRoute(sub) : `/management/points/ledger/${id}`;
|
||||
}
|
||||
|
||||
// ---------- 筛选 ----------
|
||||
|
||||
const isGlobalManager = computed(() => userStore.hasRoles(gaoRoleCodes.globalManager));
|
||||
@@ -410,38 +450,12 @@ function getLedgerTheme(item: PointLedger): string {
|
||||
return item.pointDelta && 0 < item.pointDelta ? "increase" : "decrease";
|
||||
}
|
||||
|
||||
async function toDetail(item: PointLedger): Promise<void> {
|
||||
function toDetail(item: PointLedger): void {
|
||||
if (!item.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot: PointLedger = {
|
||||
id: item.id,
|
||||
accountId: item.accountId,
|
||||
storeId: item.storeId,
|
||||
customerId: item.customerId,
|
||||
changeType: item.changeType,
|
||||
direction: item.direction,
|
||||
pointDelta: item.pointDelta,
|
||||
balanceBefore: item.balanceBefore,
|
||||
balanceAfter: item.balanceAfter,
|
||||
ruleId: item.ruleId,
|
||||
triggerSourceType: item.triggerSourceType,
|
||||
triggerSourceId: item.triggerSourceId,
|
||||
salesOrderId: item.salesOrderId,
|
||||
groovyScriptVersionId: item.groovyScriptVersionId,
|
||||
ruleSnapshot: item.ruleSnapshot,
|
||||
sourcePayload: item.sourcePayload,
|
||||
idempotencyKey: item.idempotencyKey,
|
||||
remark: item.remark,
|
||||
operatorUserId: item.operatorUserId,
|
||||
occurredAt: item.occurredAt
|
||||
};
|
||||
await router.push({
|
||||
name: "PointLedgerDetail",
|
||||
params: { id: item.id },
|
||||
query: { snapshot: JSON.stringify(snapshot) }
|
||||
});
|
||||
openDetail(item.id);
|
||||
}
|
||||
|
||||
function buildUnixRange(): [number, number] {
|
||||
|
||||
@@ -21,7 +21,11 @@
|
||||
<t-cell title="兑换数量" :note="`${quantityText(item.quantity)} ${item.unitSnapshot || ''}`" />
|
||||
<t-cell title="积分" :note="`${formatPoint(item.actualPointCost)}${item.actualPointCost !== item.defaultPointCost ? '(已减免)' : ''}`" />
|
||||
<t-cell title="状态" :note="statusText(item.status)" />
|
||||
<t-cell title="兑换时间" :note="timeText(item.redeemedAt)" />
|
||||
<t-cell title="兑换时间">
|
||||
<template #note>
|
||||
<time-label :timestamp="item.redeemedAt" underline />
|
||||
</template>
|
||||
</t-cell>
|
||||
<t-cell v-if="item.remark" title="备注" :note="item.remark" />
|
||||
<div class="photo-wrap bg-white">
|
||||
<attachment-selector :items="redemptionPhotoItems" title="兑换凭证" readonly />
|
||||
@@ -32,8 +36,12 @@
|
||||
v-for="record in returnList"
|
||||
:key="record.id"
|
||||
:title="`退货 ${quantityText(record.quantity)} ${item?.unitSnapshot || ''}`"
|
||||
:note="`${formatPoint(record.pointCost)} · ${timeText(record.returnedAt)}`"
|
||||
/>
|
||||
:note="formatPoint(record.pointCost)"
|
||||
>
|
||||
<template #description>
|
||||
<time-label :timestamp="record.returnedAt" underline />
|
||||
</template>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<t-empty v-if="!item" :description="loading ? '正在加载兑换单' : '兑换单不存在'" />
|
||||
<t-button
|
||||
@@ -96,6 +104,7 @@ import { formatWanInteger } from "@/utils/money";
|
||||
import { comparePackageQuantity, getPackageQuantityText, normalizePackageQuantity } from "@/utils/package";
|
||||
import { uploadPhotoList } from "@/utils/photo";
|
||||
import { permissionCodes } from "@/utils/permission";
|
||||
import { TimeLabel } from "timi-web";
|
||||
|
||||
defineOptions({ name: "PointRedemptionDetail" });
|
||||
|
||||
@@ -248,10 +257,6 @@ function statusText(value?: PointRedemptionStatus): string {
|
||||
} as Record<string, string>)[value || ""] || "未知";
|
||||
}
|
||||
|
||||
function timeText(value?: number): string {
|
||||
return value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "-";
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
watch(() => [props.redemptionId, route.params.id], load);
|
||||
</script>
|
||||
|
||||
@@ -191,8 +191,11 @@ defineOptions({
|
||||
const props = withDefaults(defineProps<{
|
||||
/** 指定积分规则 ID 时忽略路由参数,用于平板主从分栏的内联渲染。 */
|
||||
ruleId?: string;
|
||||
/** 在分栏中新增积分规则。 */
|
||||
create?: boolean;
|
||||
}>(), {
|
||||
ruleId: ""
|
||||
ruleId: "",
|
||||
create: false
|
||||
});
|
||||
|
||||
const route = useRoute();
|
||||
@@ -200,6 +203,9 @@ const currentId = computed(() => props.ruleId || String(route.params.id || ""));
|
||||
|
||||
const routeNavBarTitle = computed(() => {
|
||||
// 内联时路由停在列表页,标题不能只看 route.name
|
||||
if (props.create) {
|
||||
return "新增积分规则";
|
||||
}
|
||||
if (props.ruleId) {
|
||||
return "编辑积分规则";
|
||||
}
|
||||
@@ -215,11 +221,10 @@ const routeNavBarTitle = computed(() => {
|
||||
const router = useRouter();
|
||||
|
||||
// 竖屏整页编辑转横屏:回到分栏,并用 view=edit 让列表页把右栏还原成编辑。
|
||||
// 新增(Create)返回空 id,不触发——右栏没有可依附的选中项
|
||||
useExpandToMaster({
|
||||
path: "/management/points/rules",
|
||||
id: () => (route.name === "PointRuleCreate" ? "" : currentId.value),
|
||||
query: { view: "edit" }
|
||||
id: () => (route.name === "PointRuleCreate" ? "__create__" : currentId.value),
|
||||
query: route.name === "PointRuleCreate" ? {} : { view: "edit" }
|
||||
});
|
||||
/** 非空说明当前被内联在主从分栏的右栏里 */
|
||||
const pane = usePane();
|
||||
|
||||
@@ -86,7 +86,8 @@
|
||||
</t-pull-down-refresh>
|
||||
</template>
|
||||
<template #detail>
|
||||
<point-rule-edit v-if="editing" :key="`edit-${selectedId}`" :rule-id="selectedId" />
|
||||
<point-rule-edit v-if="selectedId === createPaneId" key="create" create />
|
||||
<point-rule-edit v-else-if="editing" :key="`edit-${selectedId}`" :rule-id="selectedId" />
|
||||
<point-rule-detail
|
||||
v-else
|
||||
:key="`detail-${selectedId}-${detailVersion}`"
|
||||
@@ -121,12 +122,13 @@ defineOptions({
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
const createPaneId = "__create__";
|
||||
|
||||
// 选中项、切换方向、关闭逻辑、转屏、query 同步都在这里
|
||||
const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } =
|
||||
useMasterDetailPane({
|
||||
path: "/management/points/rules",
|
||||
detail: id => `/management/points/rules/${id}`,
|
||||
detail: id => id === createPaneId ? "/management/points/rules/create" : `/management/points/rules/${id}`,
|
||||
edit: id => `/management/points/rules/${id}/edit`
|
||||
});
|
||||
const userStore = useUserStore();
|
||||
@@ -279,6 +281,12 @@ watch(keyword, () => {
|
||||
reloadByKeyword();
|
||||
});
|
||||
|
||||
watch(selectedId, async (id, previousId) => {
|
||||
if (previousId === createPaneId && id !== createPaneId) {
|
||||
await reload();
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- 事件名称 ----------
|
||||
|
||||
const eventList = ref<EventItem[]>([]);
|
||||
@@ -340,6 +348,10 @@ function getStatusTheme(status?: PointRuleStatus): "default" | "success" | "warn
|
||||
}
|
||||
|
||||
async function toCreate(): Promise<void> {
|
||||
if (isWide.value) {
|
||||
openDetail(createPaneId);
|
||||
return;
|
||||
}
|
||||
await router.push({ name: "PointRuleCreate" });
|
||||
}
|
||||
|
||||
|
||||