Files
frontend/src/services/background/ForegroundServiceModule.ts

103 lines
2.3 KiB
TypeScript
Raw Normal View History

/**
*
*
* 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;
},
};