app-settings.service.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { Injectable, InjectionToken, inject, signal } from '@angular/core';
  2. import { registerPlugin } from '@capacitor/core';
  3. import { isNativeApp } from './api/platform-proxy.service';
  4. import { UiMToastService } from '../ui/mobile/components/toast/toast';
  5. export type SettingsTarget = 'application' | 'notifications' | 'battery' | 'autostart';
  6. /** 系统页没直达时的兜底提示(按目标区分,别让用户在一堆列表里瞎找) */
  7. const FALLBACK_HINT: Record<SettingsTarget, string> = {
  8. notifications: '请在应用信息中打开「通知管理」',
  9. battery: '请在应用信息中找到「省电策略」,选择「无限制」',
  10. autostart: '请在应用信息中找到「自启动」并允许;不同品牌位置不同',
  11. application: '请在应用信息中检查相关权限',
  12. };
  13. export interface AppSettingsStatus {
  14. notificationsEnabled: boolean;
  15. manufacturer: string;
  16. /** 仅 Android 标准省电白名单;不能据此推断厂商的后台策略。 */
  17. batteryOptimizationsIgnored: boolean;
  18. }
  19. export interface SettingsOpenResult { destination: SettingsTarget; fallback: boolean; }
  20. export interface AppSettingsPlugin {
  21. open(options?: { target: SettingsTarget }): Promise<SettingsOpenResult>;
  22. getStatus(): Promise<AppSettingsStatus>;
  23. }
  24. export const APP_SETTINGS_PLUGIN = new InjectionToken<AppSettingsPlugin>('APP_SETTINGS_PLUGIN', {
  25. providedIn: 'root', factory: () => registerPlugin<AppSettingsPlugin>('AppSettings'),
  26. });
  27. export const APP_SETTINGS_NATIVE = new InjectionToken<() => boolean>('APP_SETTINGS_NATIVE', {
  28. providedIn: 'root', factory: () => isNativeApp,
  29. });
  30. @Injectable({ providedIn: 'root' })
  31. export class AppSettingsService {
  32. private readonly plugin = inject(APP_SETTINGS_PLUGIN);
  33. private readonly native = inject(APP_SETTINGS_NATIVE);
  34. private readonly toast = inject(UiMToastService);
  35. readonly status = signal<AppSettingsStatus | null>(null);
  36. async refresh(): Promise<AppSettingsStatus | null> {
  37. if (!this.native()) return null;
  38. try { const status = await this.plugin.getStatus(); this.status.set(status); return status; }
  39. catch { this.status.set(null); return null; }
  40. }
  41. async open(target: SettingsTarget): Promise<boolean> {
  42. if (!this.native()) return false;
  43. try {
  44. const result = await this.plugin.open({ target });
  45. if (result.fallback) this.toast.info(FALLBACK_HINT[target] ?? FALLBACK_HINT.application);
  46. return true;
  47. } catch {
  48. this.toast.error('未能打开设置,请长按 Fmode 图标进入「应用信息」');
  49. return false;
  50. }
  51. }
  52. }