feat(service): add foreground service for background message sync
Implement Android foreground service to keep app alive in background for real-time message sync: - Add withForegroundService expo config plugin for notification channel setup - Add BackgroundSyncManager with REALTIME, BATTERY_SAVER, and DISABLED modes - Add ForegroundServiceModule for native Android foreground service binding - Refactor backgroundService to integrate foreground service and expo-background-task Also refactor auth and profile screens to use dynamic theme colors: - Replace hardcoded THEME_COLORS with colors.primary.main, colors.background.paper, etc. - Add useResolvedColorScheme for dynamic StatusBar styling - Update NotificationSettingsScreen with sync mode selection UI BREAKING CHANGE: Switched from expo-background-fetch to expo-background-task, minimum background sync interval changed from 900s to 15min in config
This commit is contained in:
284
src/services/BackgroundSyncManager.ts
Normal file
284
src/services/BackgroundSyncManager.ts
Normal file
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* 后台同步管理器
|
||||
*
|
||||
* 整合前台服务、后台同步、消息状态管理
|
||||
* 参考 Element Android 的 BackgroundSyncStarter 设计
|
||||
*/
|
||||
|
||||
import { AppState, AppStateStatus, Platform } from 'react-native';
|
||||
import { ForegroundServiceModule } from './ForegroundServiceModule';
|
||||
import { wsService } from './wsService';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
/**
|
||||
* 后台同步模式
|
||||
*/
|
||||
export enum BackgroundSyncMode {
|
||||
/** 省电模式:使用 expo-background-task(最小15分钟间隔) */
|
||||
BATTERY_SAVER = 'battery_saver',
|
||||
|
||||
/** 实时模式:前台服务保活 + 持续同步 */
|
||||
REALTIME = 'realtime',
|
||||
|
||||
/** 禁用后台同步 */
|
||||
DISABLED = 'disabled',
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'background_sync_mode';
|
||||
const SYNC_INTERVAL_MS = 30 * 1000; // 30 秒同步间隔
|
||||
|
||||
class BackgroundSyncManager {
|
||||
private mode: BackgroundSyncMode = BackgroundSyncMode.BATTERY_SAVER;
|
||||
private appStateSubscription: ReturnType<typeof AppState.addEventListener> | null = null;
|
||||
private syncInterval: ReturnType<typeof setInterval> | null = null;
|
||||
private isInitialized: boolean = false;
|
||||
private lastSyncAt: number = 0;
|
||||
private syncMessagesCallback: (() => Promise<void>) | null = null;
|
||||
|
||||
/**
|
||||
* 设置消息同步回调函数
|
||||
* 由外部注入,避免循环依赖
|
||||
*/
|
||||
setSyncMessagesCallback(callback: () => Promise<void>): void {
|
||||
this.syncMessagesCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化后台同步
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this.isInitialized) return;
|
||||
|
||||
// 加载保存的模式
|
||||
const savedMode = await this.loadMode();
|
||||
this.mode = savedMode;
|
||||
|
||||
// 监听 AppState 变化
|
||||
this.appStateSubscription = AppState.addEventListener(
|
||||
'change',
|
||||
this.handleAppStateChange
|
||||
);
|
||||
|
||||
// 监听 WebSocket 断开
|
||||
this.setupWSDisconnectListener();
|
||||
|
||||
this.isInitialized = true;
|
||||
console.log('[BackgroundSyncManager] 初始化完成, 模式:', this.mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换后台同步模式
|
||||
*/
|
||||
async setMode(mode: BackgroundSyncMode): Promise<void> {
|
||||
// 如果当前在后台,先停止旧模式的保活
|
||||
if (AppState.currentState !== 'active') {
|
||||
this.stopPeriodicSync();
|
||||
if (this.mode === BackgroundSyncMode.REALTIME) {
|
||||
await ForegroundServiceModule.stop();
|
||||
}
|
||||
}
|
||||
|
||||
// 更新模式
|
||||
this.mode = mode;
|
||||
await this.saveMode(mode);
|
||||
|
||||
// 根据新模式立即执行相应操作
|
||||
if (mode === BackgroundSyncMode.REALTIME) {
|
||||
// 切换到实时模式:立即启动前台服务(无论前台还是后台)
|
||||
const started = await ForegroundServiceModule.start({
|
||||
title: '萝卜社区',
|
||||
body: '正在后台同步消息',
|
||||
});
|
||||
if (started) {
|
||||
this.startPeriodicSync();
|
||||
}
|
||||
} else {
|
||||
// 切换到其他模式:立即停止前台服务和定时同步
|
||||
this.stopPeriodicSync();
|
||||
await ForegroundServiceModule.stop();
|
||||
}
|
||||
|
||||
console.log('[BackgroundSyncManager] 模式已切换为:', mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前模式
|
||||
*/
|
||||
getMode(): BackgroundSyncMode {
|
||||
return this.mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* AppState 变化处理
|
||||
*/
|
||||
private handleAppStateChange = async (nextState: AppStateStatus) => {
|
||||
console.log('[BackgroundSyncManager] AppState 变化:', nextState);
|
||||
|
||||
if (nextState === 'background' || nextState === 'inactive') {
|
||||
// 进入后台
|
||||
await this.startForBackground();
|
||||
} else if (nextState === 'active') {
|
||||
// 回到前台
|
||||
await this.stopForForeground();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 进入后台时的处理
|
||||
*/
|
||||
private async startForBackground(): Promise<void> {
|
||||
if (this.mode === BackgroundSyncMode.DISABLED) return;
|
||||
|
||||
console.log('[BackgroundSyncManager] 进入后台');
|
||||
|
||||
if (this.mode === BackgroundSyncMode.REALTIME) {
|
||||
// 确保前台服务正在运行
|
||||
await ForegroundServiceModule.start({
|
||||
title: '萝卜社区',
|
||||
body: '正在后台同步消息',
|
||||
});
|
||||
|
||||
// 启动定时同步
|
||||
this.startPeriodicSync();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回到前台时的处理
|
||||
*/
|
||||
private async stopForForeground(): Promise<void> {
|
||||
console.log('[BackgroundSyncManager] 回到前台');
|
||||
|
||||
// 停止定时同步(前台通过 WebSocket 实时同步,不需要轮询)
|
||||
this.stopPeriodicSync();
|
||||
|
||||
// 实时模式下:前台服务保持运行,只更新通知文字
|
||||
if (this.mode === BackgroundSyncMode.REALTIME) {
|
||||
await ForegroundServiceModule.update('萝卜社区', '正在后台同步消息');
|
||||
}
|
||||
|
||||
// 立即同步一次(获取离线消息)
|
||||
await this.syncMessages();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定时同步
|
||||
*/
|
||||
private startPeriodicSync(): void {
|
||||
this.stopPeriodicSync();
|
||||
|
||||
// 立即同步一次
|
||||
this.syncMessages();
|
||||
|
||||
// 启动定时器
|
||||
this.syncInterval = setInterval(() => {
|
||||
this.syncMessages();
|
||||
}, SYNC_INTERVAL_MS);
|
||||
|
||||
console.log('[BackgroundSyncManager] 定时同步已启动');
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止定时同步
|
||||
*/
|
||||
private stopPeriodicSync(): void {
|
||||
if (this.syncInterval) {
|
||||
clearInterval(this.syncInterval);
|
||||
this.syncInterval = null;
|
||||
console.log('[BackgroundSyncManager] 定时同步已停止');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 WebSocket 断开监听
|
||||
*/
|
||||
private setupWSDisconnectListener(): void {
|
||||
// 监听 WebSocket 断开事件
|
||||
wsService.onDisconnect(() => {
|
||||
if (AppState.currentState !== 'active' && this.mode === BackgroundSyncMode.REALTIME) {
|
||||
console.log('[BackgroundSyncManager] WebSocket 断开,尝试重连');
|
||||
wsService.connect().catch((e) => {
|
||||
console.error('[BackgroundSyncManager] WebSocket 重连失败:', e);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行消息同步
|
||||
*/
|
||||
async syncMessages(): Promise<void> {
|
||||
const now = Date.now();
|
||||
|
||||
// 防止短时间内重复同步(最小 10 秒间隔)
|
||||
if (now - this.lastSyncAt < 10000) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastSyncAt = now;
|
||||
|
||||
// 调用外部注入的同步回调
|
||||
if (this.syncMessagesCallback) {
|
||||
try {
|
||||
await this.syncMessagesCallback();
|
||||
} catch (error) {
|
||||
console.error('[BackgroundSyncManager] 同步失败:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新前台服务通知内容
|
||||
*/
|
||||
async updateNotification(totalUnread: number): Promise<void> {
|
||||
if (this.mode !== BackgroundSyncMode.REALTIME) return;
|
||||
|
||||
if (totalUnread > 0) {
|
||||
await ForegroundServiceModule.update(
|
||||
'萝卜社区',
|
||||
`您有 ${totalUnread} 条未读消息`
|
||||
);
|
||||
} else {
|
||||
await ForegroundServiceModule.update(
|
||||
'萝卜社区',
|
||||
'正在后台同步消息'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存模式到存储
|
||||
*/
|
||||
private async saveMode(mode: BackgroundSyncMode): Promise<void> {
|
||||
try {
|
||||
await AsyncStorage.setItem(STORAGE_KEY, mode);
|
||||
} catch (error) {
|
||||
console.error('[BackgroundSyncManager] 保存模式失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从存储加载模式
|
||||
*/
|
||||
private async loadMode(): Promise<BackgroundSyncMode> {
|
||||
try {
|
||||
const saved = await AsyncStorage.getItem(STORAGE_KEY);
|
||||
return (saved as BackgroundSyncMode) || BackgroundSyncMode.BATTERY_SAVER;
|
||||
} catch (error) {
|
||||
return BackgroundSyncMode.BATTERY_SAVER;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理资源
|
||||
*/
|
||||
async cleanup(): Promise<void> {
|
||||
this.stopPeriodicSync();
|
||||
this.appStateSubscription?.remove();
|
||||
this.appStateSubscription = null;
|
||||
await ForegroundServiceModule.stop();
|
||||
this.isInitialized = false;
|
||||
}
|
||||
}
|
||||
|
||||
export const backgroundSyncManager = new BackgroundSyncManager();
|
||||
102
src/services/ForegroundServiceModule.ts
Normal file
102
src/services/ForegroundServiceModule.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 前台服务模块
|
||||
*
|
||||
* 提供 React Native 层对 Android 前台服务的控制接口
|
||||
* 仅 Android 平台有效
|
||||
*/
|
||||
|
||||
import { NativeModules, Platform } from 'react-native';
|
||||
|
||||
const { ForegroundService } = NativeModules;
|
||||
|
||||
export interface ForegroundServiceOptions {
|
||||
title?: string;
|
||||
body?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 前台服务管理器
|
||||
*
|
||||
* 使用方式:
|
||||
* - 前台服务启动后,会在通知栏显示一个常驻通知
|
||||
* - 服务会防止应用进程被系统杀死
|
||||
* - 类似 V2Ray 和 Element Android 的保活机制
|
||||
*/
|
||||
export const ForegroundServiceModule = {
|
||||
/**
|
||||
* 启动前台服务
|
||||
* @param options 通知配置
|
||||
*/
|
||||
async start(options: ForegroundServiceOptions = {}): Promise<boolean> {
|
||||
if (Platform.OS !== 'android') {
|
||||
console.log('[ForegroundService] iOS 不支持前台服务保活');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!ForegroundService) {
|
||||
console.error('[ForegroundService] 原生模块未注册');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await ForegroundService.start(
|
||||
options.title || '萝卜社区',
|
||||
options.body || '正在后台同步消息'
|
||||
);
|
||||
console.log('[ForegroundService] 服务已启动');
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('[ForegroundService] 启动失败:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 停止前台服务
|
||||
*/
|
||||
async stop(): Promise<boolean> {
|
||||
if (Platform.OS !== 'android') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!ForegroundService) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await ForegroundService.stop();
|
||||
console.log('[ForegroundService] 服务已停止');
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('[ForegroundService] 停止失败:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 更新通知内容
|
||||
*/
|
||||
async update(title: string, body: string): Promise<boolean> {
|
||||
if (Platform.OS !== 'android') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!ForegroundService) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return await ForegroundService.update(title, body);
|
||||
} catch (error) {
|
||||
console.error('[ForegroundService] 更新失败:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 检查是否为 Android 平台
|
||||
*/
|
||||
isSupported(): boolean {
|
||||
return Platform.OS === 'android' && !!ForegroundService;
|
||||
},
|
||||
};
|
||||
@@ -1,107 +1,92 @@
|
||||
/**
|
||||
* 后台保活服务
|
||||
* 使用 expo-background-fetch 和 expo-task-manager 实现 App 后台保活
|
||||
*
|
||||
* 功能:
|
||||
* - 定期后台任务保持 App 在内存中
|
||||
* - 配合 SSE 服务保持长连接
|
||||
* - 收到消息时触发震动提示
|
||||
* 整合前台服务和后台同步
|
||||
* - REALTIME 模式:使用 Android 前台服务保活(通知栏常驻)
|
||||
* - BATTERY_SAVER 模式:使用 expo-background-task 定期同步(最小15分钟间隔)
|
||||
*
|
||||
* 参考:Element Android 的 GuardAndroidService + BackgroundSyncStarter
|
||||
*/
|
||||
|
||||
import { AppState, AppStateStatus, Platform } from 'react-native';
|
||||
import * as BackgroundFetch from 'expo-background-fetch';
|
||||
import { Platform } from 'react-native';
|
||||
import * as BackgroundTask from 'expo-background-task';
|
||||
import * as TaskManager from 'expo-task-manager';
|
||||
import { wsService } from './wsService';
|
||||
import {
|
||||
triggerVibration,
|
||||
vibrateOnMessage,
|
||||
setVibrationConfig,
|
||||
getVibrationConfig,
|
||||
setVibrationEnabled,
|
||||
} from './messageVibrationService';
|
||||
export { triggerVibration, vibrateOnMessage, setVibrationConfig, getVibrationConfig, setVibrationEnabled };
|
||||
|
||||
// 后台任务名称
|
||||
const BACKGROUND_FETCH_TASK = 'background-fetch-keepalive';
|
||||
const REALTIME_KEEPALIVE_TASK = 'realtime-keepalive';
|
||||
|
||||
// 后台任务间隔(Android 最小 15 分钟,iOS 最小 15 分钟)
|
||||
const BACKGROUND_INTERVAL = 15; // 15 分钟
|
||||
|
||||
// 后台服务状态
|
||||
let isInitialized = false;
|
||||
let appStateSubscription: any = null;
|
||||
|
||||
// 导入 api 用于检查认证状态
|
||||
backgroundSyncManager,
|
||||
BackgroundSyncMode,
|
||||
} from './BackgroundSyncManager';
|
||||
import { messageService } from './messageService';
|
||||
import { api } from './api';
|
||||
|
||||
// 定义后台任务
|
||||
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
|
||||
// 后台任务名称
|
||||
const BACKGROUND_SYNC_TASK = 'background-sync-task';
|
||||
|
||||
// 后台任务间隔(分钟)
|
||||
const BACKGROUND_INTERVAL_MINUTES = 15;
|
||||
|
||||
// 服务状态
|
||||
let isInitialized = false;
|
||||
|
||||
// 定义后台任务(使用 expo-background-task)
|
||||
TaskManager.defineTask(BACKGROUND_SYNC_TASK, async () => {
|
||||
try {
|
||||
// 检查是否已认证
|
||||
const token = await api.getToken();
|
||||
if (!token) {
|
||||
return BackgroundFetch.BackgroundFetchResult.NoData;
|
||||
return BackgroundTask.BackgroundTaskResult.Success;
|
||||
}
|
||||
|
||||
// 检查 SSE 连接状态
|
||||
if (!wsService.isConnected()) {
|
||||
await wsService.connect();
|
||||
}
|
||||
|
||||
// 返回收到新数据
|
||||
return BackgroundFetch.BackgroundFetchResult.NewData;
|
||||
|
||||
// 执行同步
|
||||
await syncMessages();
|
||||
|
||||
return BackgroundTask.BackgroundTaskResult.Success;
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 后台任务执行失败:', error);
|
||||
return BackgroundFetch.BackgroundFetchResult.Failed;
|
||||
}
|
||||
});
|
||||
|
||||
// SSE 保活任务
|
||||
TaskManager.defineTask(REALTIME_KEEPALIVE_TASK, async () => {
|
||||
try {
|
||||
// 检查是否已认证
|
||||
const token = await api.getToken();
|
||||
if (!token) {
|
||||
return BackgroundFetch.BackgroundFetchResult.NoData;
|
||||
}
|
||||
|
||||
if (!wsService.isConnected()) {
|
||||
await wsService.connect();
|
||||
}
|
||||
return BackgroundFetch.BackgroundFetchResult.NewData;
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] SSE 保活失败:', error);
|
||||
return BackgroundFetch.BackgroundFetchResult.Failed;
|
||||
return BackgroundTask.BackgroundTaskResult.Failed;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 注册后台任务
|
||||
* 执行消息同步
|
||||
*/
|
||||
async function registerBackgroundTasks(): Promise<void> {
|
||||
async function syncMessages(): Promise<void> {
|
||||
try {
|
||||
// 同步未读数
|
||||
const unreadData = await messageService.getUnreadCount();
|
||||
const totalUnread = unreadData?.total_unread_count ?? 0;
|
||||
|
||||
// 更新前台服务通知
|
||||
await backgroundSyncManager.updateNotification(totalUnread);
|
||||
|
||||
console.log('[BackgroundService] 同步完成, 未读数:', totalUnread);
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 同步失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册后台任务(expo-background-task)
|
||||
*/
|
||||
async function registerBackgroundTask(): Promise<void> {
|
||||
if (Platform.OS === 'web') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 检查是否已注册
|
||||
const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_FETCH_TASK);
|
||||
if (!isRegistered) {
|
||||
await BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
|
||||
minimumInterval: BACKGROUND_INTERVAL * 60, // 转换为秒
|
||||
stopOnTerminate: false, // App 终止后继续运行
|
||||
startOnBoot: true, // 设备启动后自动运行
|
||||
});
|
||||
// 检查后台任务状态
|
||||
const status = await BackgroundTask.getStatusAsync();
|
||||
if (status !== BackgroundTask.BackgroundTaskStatus.Available) {
|
||||
console.warn('[BackgroundService] 后台任务不可用,状态:', status);
|
||||
return;
|
||||
}
|
||||
|
||||
// 注册 SSE 保活任务
|
||||
const isSseKeepaliveRegistered = await TaskManager.isTaskRegisteredAsync(REALTIME_KEEPALIVE_TASK);
|
||||
if (!isSseKeepaliveRegistered) {
|
||||
await BackgroundFetch.registerTaskAsync(REALTIME_KEEPALIVE_TASK, {
|
||||
minimumInterval: 60, // 1 分钟检查一次
|
||||
stopOnTerminate: false,
|
||||
startOnBoot: true,
|
||||
// 检查是否已注册
|
||||
const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_SYNC_TASK);
|
||||
if (!isRegistered) {
|
||||
await BackgroundTask.registerTaskAsync(BACKGROUND_SYNC_TASK, {
|
||||
minimumInterval: BACKGROUND_INTERVAL_MINUTES, // 以分钟为单位
|
||||
});
|
||||
console.log('[BackgroundService] 后台任务已注册');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 注册后台任务失败:', error);
|
||||
@@ -111,41 +96,22 @@ async function registerBackgroundTasks(): Promise<void> {
|
||||
/**
|
||||
* 取消后台任务
|
||||
*/
|
||||
async function unregisterBackgroundTasks(): Promise<void> {
|
||||
async function unregisterBackgroundTask(): Promise<void> {
|
||||
if (Platform.OS === 'web') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await BackgroundFetch.unregisterTaskAsync(BACKGROUND_FETCH_TASK);
|
||||
await BackgroundFetch.unregisterTaskAsync(REALTIME_KEEPALIVE_TASK);
|
||||
const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_SYNC_TASK);
|
||||
if (isRegistered) {
|
||||
await BackgroundTask.unregisterTaskAsync(BACKGROUND_SYNC_TASK);
|
||||
console.log('[BackgroundService] 后台任务已取消');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 取消后台任务失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 App 状态监听
|
||||
*/
|
||||
function setupAppStateListener(): void {
|
||||
if (appStateSubscription) {
|
||||
return;
|
||||
}
|
||||
|
||||
appStateSubscription = AppState.addEventListener('change', async (nextAppState: AppStateStatus) => {
|
||||
if (nextAppState === 'active') {
|
||||
// 检查是否已认证
|
||||
const token = await api.getToken();
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
// App 回到前台,确保连接
|
||||
if (!wsService.isConnected()) {
|
||||
wsService.connect();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化后台保活服务
|
||||
*/
|
||||
@@ -155,26 +121,22 @@ export async function initBackgroundService(): Promise<boolean> {
|
||||
}
|
||||
|
||||
if (Platform.OS === 'web') {
|
||||
setupAppStateListener();
|
||||
isInitialized = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
// 检查后台任务状态
|
||||
const status = await BackgroundFetch.getStatusAsync();
|
||||
if (status !== BackgroundFetch.BackgroundFetchStatus.Available) {
|
||||
console.warn('[BackgroundService] 后台任务不可用,状态:', status);
|
||||
// 即使后台任务不可用,也继续初始化其他功能
|
||||
}
|
||||
// 设置同步回调
|
||||
backgroundSyncManager.setSyncMessagesCallback(syncMessages);
|
||||
|
||||
// 注册后台任务
|
||||
await registerBackgroundTasks();
|
||||
// 初始化后台同步管理器
|
||||
await backgroundSyncManager.initialize();
|
||||
|
||||
// 设置 App 状态监听
|
||||
setupAppStateListener();
|
||||
// 注册 expo-background-task 任务(用于 BATTERY_SAVER 模式)
|
||||
await registerBackgroundTask();
|
||||
|
||||
isInitialized = true;
|
||||
console.log('[BackgroundService] 初始化完成');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 初始化失败:', error);
|
||||
@@ -187,14 +149,10 @@ export async function initBackgroundService(): Promise<boolean> {
|
||||
*/
|
||||
export async function stopBackgroundService(): Promise<void> {
|
||||
try {
|
||||
await unregisterBackgroundTasks();
|
||||
|
||||
if (appStateSubscription) {
|
||||
appStateSubscription.remove();
|
||||
appStateSubscription = null;
|
||||
}
|
||||
|
||||
await unregisterBackgroundTask();
|
||||
await backgroundSyncManager.cleanup();
|
||||
isInitialized = false;
|
||||
console.log('[BackgroundService] 服务已停止');
|
||||
} catch (error) {
|
||||
console.error('[BackgroundService] 停止服务失败:', error);
|
||||
}
|
||||
@@ -207,34 +165,74 @@ export async function checkBackgroundStatus(): Promise<{
|
||||
isAvailable: boolean;
|
||||
isInitialized: boolean;
|
||||
registeredTasks: string[];
|
||||
mode: BackgroundSyncMode;
|
||||
}> {
|
||||
if (Platform.OS === 'web') {
|
||||
return {
|
||||
isAvailable: false,
|
||||
isInitialized,
|
||||
registeredTasks: [],
|
||||
mode: backgroundSyncManager.getMode(),
|
||||
};
|
||||
}
|
||||
const status = await BackgroundFetch.getStatusAsync();
|
||||
|
||||
const status = await BackgroundTask.getStatusAsync();
|
||||
const registeredTasks = await TaskManager.getRegisteredTasksAsync();
|
||||
|
||||
return {
|
||||
isAvailable: status === BackgroundFetch.BackgroundFetchStatus.Available,
|
||||
isAvailable: status === BackgroundTask.BackgroundTaskStatus.Available,
|
||||
isInitialized,
|
||||
registeredTasks: registeredTasks.map(task => task.taskName),
|
||||
registeredTasks: registeredTasks.map((task) => task.taskName),
|
||||
mode: backgroundSyncManager.getMode(),
|
||||
};
|
||||
}
|
||||
|
||||
// 导出服务实例
|
||||
export const backgroundService = {
|
||||
init: initBackgroundService,
|
||||
stop: stopBackgroundService,
|
||||
vibrate: triggerVibration,
|
||||
/**
|
||||
* 设置后台同步模式
|
||||
*/
|
||||
export async function setBackgroundSyncMode(mode: BackgroundSyncMode): Promise<void> {
|
||||
await backgroundSyncManager.setMode(mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前后台同步模式
|
||||
*/
|
||||
export function getBackgroundSyncMode(): BackgroundSyncMode {
|
||||
return backgroundSyncManager.getMode();
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动触发同步
|
||||
*/
|
||||
export async function syncNow(): Promise<void> {
|
||||
await syncMessages();
|
||||
}
|
||||
|
||||
// 导出震动相关功能(保持向后兼容)
|
||||
export {
|
||||
triggerVibration,
|
||||
vibrateOnMessage,
|
||||
setVibrationConfig,
|
||||
getVibrationConfig,
|
||||
setVibrationEnabled,
|
||||
} from './messageVibrationService';
|
||||
|
||||
// 重新导出类型
|
||||
export { BackgroundSyncMode };
|
||||
|
||||
// 后台服务实例
|
||||
export const backgroundService = {
|
||||
init: initBackgroundService,
|
||||
stop: stopBackgroundService,
|
||||
setMode: setBackgroundSyncMode,
|
||||
getMode: getBackgroundSyncMode,
|
||||
syncNow,
|
||||
checkStatus: checkBackgroundStatus,
|
||||
// 震动相关
|
||||
vibrate: async () => {
|
||||
const { triggerVibration } = await import('./messageVibrationService');
|
||||
triggerVibration();
|
||||
},
|
||||
};
|
||||
|
||||
export default backgroundService;
|
||||
|
||||
Reference in New Issue
Block a user