diff --git a/src/services/apkUpdateService.ts b/src/services/apkUpdateService.ts index 6d2de6d..55ba1db 100644 --- a/src/services/apkUpdateService.ts +++ b/src/services/apkUpdateService.ts @@ -5,11 +5,22 @@ import { Platform, Linking, Alert } from 'react-native'; import Constants from 'expo-constants'; -import * as FileSystem from 'expo-file-system/legacy'; -import * as IntentLauncher from 'expo-intent-launcher'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { showConfirm } from './dialogService'; +// 条件导入原生模块(仅在 Android 上可用) +let FileSystem: typeof import('expo-file-system/legacy') | null = null; +let IntentLauncher: typeof import('expo-intent-launcher') | null = null; + +if (Platform.OS === 'android') { + try { + FileSystem = require('expo-file-system/legacy'); + IntentLauncher = require('expo-intent-launcher'); + } catch (e) { + console.warn('Failed to load native modules for APK update:', e); + } +} + // 更新服务器地址 const UPDATES_SERVER_URL = Constants.expoConfig?.extra?.updatesUrl ? Constants.expoConfig.extra.updatesUrl.replace('/api/manifest', '') @@ -133,6 +144,12 @@ async function downloadAndInstallAPK(downloadUrl: string, version: string): Prom return; } + if (!FileSystem) { + Alert.alert('提示', '当前环境不支持 APK 更新,请在浏览器中下载'); + Linking.openURL(downloadUrl); + return; + } + try { const downloadPath = `${FileSystem.documentDirectory}carrot-bbs-${version}.apk`; @@ -171,6 +188,10 @@ async function downloadAndInstallAPK(downloadUrl: string, version: string): Prom */ async function installAPK(apkUri: string): Promise { try { + if (!FileSystem || !IntentLauncher) { + throw new Error('Native modules not available'); + } + // 获取文件的 content URI const contentUri = await FileSystem.getContentUriAsync(apkUri); @@ -182,8 +203,7 @@ async function installAPK(apkUri: string): Promise { } catch (error) { console.error('Install APK error:', error); // 尝试使用浏览器下载 - const webUrl = apkUri.replace('file://', ''); - Linking.openURL(webUrl); + Linking.openURL(apkUri.replace('file://', '')); } }