Files
frontend/src/services/background/ForegroundServiceModule.ts
lafay fe6a03da5d
Some checks failed
Frontend CI / build-and-push-web (push) Successful in 2m39s
Frontend CI / ota-android (push) Successful in 10m22s
Frontend CI / build-android-apk (push) Has been cancelled
feat: 优化架构
2026-04-13 01:30:37 +08:00

103 lines
2.3 KiB
TypeScript

/**
* 前台服务模块
*
* 提供 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;
},
};