feat(core): ready to native bridge
This commit is contained in:
@@ -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 映射算法。
|
||||
@@ -15,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.
|
||||
@@ -43,6 +43,11 @@ android {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 与 capacitor-android 保持一致,避免 JVM target 不一致的编译告警
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_21
|
||||
targetCompatibility JavaVersion.VERSION_21
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
@@ -57,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,17 +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) {
|
||||
@@ -43,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,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 "";
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -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);
|
||||
}
|
||||
}
|
||||
+468
@@ -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";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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'
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user